Python指令碼實現12306火車票查詢系統_python

來源:互聯網
上載者:User

最近我看到看到使用python實現火車票查詢,我自己也實現了,感覺收穫蠻多的,下面我就把每一步驟都詳細給分享出來。(注意使用的是python3)

首先我將最終結果給展示出來:

在cmd命令列執行:python tickets.py -dk shanghai chengdu 20161007 > result.txt

意思是:查詢 上海--成都 2016.10.07 的D和K開頭的列車資訊,並儲存到 result.txt檔案中;下面就是result.txt檔案中的結果:

下面的將是實現步驟:

1、安裝第三方庫 pip install 安裝:requests,docopt,prettytable

2、docopt可以用來解析從命令列中輸入的參數:

"""Usage:test [-gdtkz] <from> <to> <date>Options:-h,--help 顯示協助菜單-g 高鐵-d 動車-t 特快-k 快速-z 直達Example:tickets -gdt beijing shanghai 2016-08-25"""import docoptargs = docopt.docopt(__doc__)print(args)# 上面 """ """ 包含中的:#Usage:# test [-gdtkz] <from> <to> <date>#是必須要的 test 是可以隨便寫的,不影響解析

最終列印的結果是一個字典,方便後面使用:

3、擷取列車的資訊

我們在12306的餘票查詢的介面:

url:https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-10-05&from_station=CDW&to_station=SHH

方法為:get

傳輸的參數:queryDate:2016-10-05、from_station:CDW、to_station:SHH

其中城市對應簡稱是需要另外的介面查詢得出

3.1 查詢城市對應的簡稱:

這個介面的url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8968'

  方法是get,對返回結果利用Regex,取出城市名和簡稱的值(返回的值類似:7@cqn|重慶南|CRW|chongqingnan|cqn|,我們需要的就是:CRW、chongqingnan),代碼如下

parse_stations.py:

#coding=utf-8from prettytable import PrettyTableclass TrainCollection(object):"""解析列車資訊"""# 顯示車次、出發/到達站、 出發/到達時間、曆時、一等坐、二等坐、軟臥、硬臥、硬座header = '序號 車次 出發站/到達站 出發時間/到達時間 曆時 商務座 一等座 二等座 軟臥 硬臥 硬座 無座'.split()def __init__(self,rows,traintypes):self.rows = rowsself.traintypes = traintypesdef _get_duration(self,row):"""擷取車次啟動並執行時間"""duration = row.get('lishi').replace(':','小時') + '分'if duration.startswith('00'):return duration[4:]elif duration.startswith('0'):return duration[1:]return duration@propertydef trains(self):result = []flag = 0for row in self.rows:if row['station_train_code'][0] in self.traintypes:flag += 1train = [# 序號flag,# 車次row['station_train_code'],# 出發、到達網站'/'.join([row['from_station_name'],row['to_station_name']]),# 成功、到達時間'/'.join([row['start_time'],row['arrive_time']]),# duration 時間self._get_duration(row),# 商務座row['swz_num'],# 一等座row['zy_num'],# 二等座row['ze_num'],# 軟臥row['rw_num'],# 硬臥row['yw_num'],# 硬座row['yz_num'],# 無座row['wz_num']]result.append(train)return resultdef print_pretty(self):"""列印列車資訊"""pt = PrettyTable()pt._set_field_names(self.header)for train in self.trains:pt.add_row(train)print(pt)if __name__ == '__main__':t = TrainCollection()

其中pprint這個模組能是列印出來的資訊,更加方便閱讀:

在cmd中運行:python parse_stations.py > stations.py

就會在目前的目錄下得到stations.py檔案,檔案中就是網站名字和簡稱,在stations.py檔案中加入"stations = "這樣就是一個字典,方便後面的取值,下面就是stations.py檔案的內容:

3.2 現在擷取列車資訊的參數已經準備齊了,接下來就是拿到列車的傳回值,解析出自己需要的資訊,比如:車次號,一等座的票數等等。。,myprettytable.py

#coding=utf-8from prettytable import PrettyTableclass TrainCollection(object):"""解析列車資訊"""# 顯示車次、出發/到達站、 出發/到達時間、曆時、一等坐、二等坐、軟臥、硬臥、硬座header = '序號 車次 出發站/到達站 出發時間/到達時間 曆時 商務座 一等座 二等座 軟臥 硬臥 硬座 無座'.split()def __init__(self,rows,traintypes):self.rows = rowsself.traintypes = traintypesdef _get_duration(self,row):"""擷取車次啟動並執行時間"""duration = row.get('lishi').replace(':','小時') + '分'if duration.startswith('00'):return duration[4:]elif duration.startswith('0'):return duration[1:]return duration@propertydef trains(self):result = []flag = 0for row in self.rows:if row['station_train_code'][0] in self.traintypes:flag += 1train = [# 序號flag,# 車次row['station_train_code'],# 出發、到達網站'/'.join([row['from_station_name'],row['to_station_name']]),# 成功、到達時間'/'.join([row['start_time'],row['arrive_time']]),# duration 時間self._get_duration(row),# 商務座row['swz_num'],# 一等座row['zy_num'],# 二等座row['ze_num'],# 軟臥row['rw_num'],# 硬臥row['yw_num'],# 硬座row['yz_num'],# 無座row['wz_num']]result.append(train)return resultdef print_pretty(self):"""列印列車資訊"""pt = PrettyTable()pt._set_field_names(self.header)for train in self.trains:pt.add_row(train)print(pt)if __name__ == '__main__':t = TrainCollection()

prettytable 這個庫是能列印出類似mysql查詢資料顯示出來的格式,

4、接下來就是整合各個模組:tickets.py

"""Train tickets query via command-line.Usage:tickets [-gdtkz] <from> <to> <date>Options:-h,--help 顯示協助菜單-g 高鐵-d 動車-t 特快-k 快速-z 直達Example:tickets -gdt beijing shanghai 2016-08-25"""import requestsfrom docopt import docoptfrom stations import stations# from pprint import pprintfrom myprettytable import TrainCollectionclass SelectTrain(object):def __init__(self):"""擷取命令列輸入的參數"""self.args = docopt(__doc__)#這個是擷取命令列的所有參數,返回的是一個字典def cli(self):"""command-line interface"""# 擷取 出發網站和目標網站from_station = stations.get(self.args['<from>']) #出發網站to_station = stations.get(self.args['<to>']) # 目的網站leave_time = self._get_leave_time()# 出發時間url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={0}&from_station={1}&to_station={2}'.format(leave_time,from_station,to_station)# 拼接請求列車資訊的Url# 擷取列車查詢結果r = requests.get(url,verify=False)traindatas = r.json()['data']['datas'] # 返回的結果,轉化成json格式,取出datas,方便後面解析列車資訊用# 解析列車資訊traintypes = self._get_traintype()views = TrainCollection(traindatas,traintypes)views.print_pretty()def _get_traintype(self):"""擷取列車型號,這個函數的作用是的目的是:當你輸入 -g 是只是返回 高鐵,輸入 -gd 返回動車和高鐵,當不輸參數時,返回所有的列車資訊""" traintypes = ['-g','-d','-t','-k','-z']# result = []# for traintype in traintypes:# if self.args[traintype]:# result.append(traintype[-1].upper())trains = [traintype[-1].upper() for traintype in traintypes if self.args[traintype]]if trains:return trainselse:return ['G','D','T','K','Z']def _get_leave_time(self):"""擷取出發時間,這個函數的作用是為了:時間可以輸入兩種格式:2016-10-05、20161005"""leave_time = self.args['<date>']if len(leave_time) == 8:return '{0}-{1}-{2}'.format(leave_time[:4],leave_time[4:6],leave_time[6:])if '-' in leave_time:return leave_timeif __name__ == '__main__':cli = SelectTrain()cli.cli()

好了,基本上就結束了,按照開頭的哪樣,就能查詢你想要的車次資訊了

以上所述是小編給大家介紹的Python指令碼實現12306火車票查詢系統,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.