使用python腳本實現查詢火車票信息的效果圖如下:
實現的代碼:
# coding: utf-8"""命令行火車票查看器Usage: tickets [-gdtkz] Options: -h,--help 顯示幫助菜單 -g 高鐵 -d 動車 -t 特快 -k 快速 -z 直達Example: tickets 北京 上海 2016-10-10 tickets -dg 成都 南京 2016-10-10"""import jsonimport requestsimport prettytablefrom docopt import docoptfrom colorama import init, Foreclass CollectInfo: def __init__(self): self.qurey_ret = [] self.header = ['車次信息', '發/到時間', '發/到站', '歷時', '票價', '余票'] # 獲取車次相關的所有信息 def query_html_ret(self, query_args): url = 'http://api.12306.com/v1/train/trainInfos?arrStationCode={to_station}&deptDate={date}/ &deptStationCode={source_station}&findGD=false'.format(to_station=query_args['to_station'], source_station=query_args['source_station'], date=query_args['date']) row_ret = requests.get(url) return row_ret.json() # 解析獲取到的結果 def paser_ret(self, row_ret): trains_info = row_ret['data']['trainInfos'] for info in trains_info: row_info = [] # 獲取車次信息 row_info.append('/n' + info['trainCode']) # 獲取車次到站時間信息 row_info.append('/n' + '/n'.join([Fore.GREEN + info['deptTime']+ Fore.RESET, Fore.RED + info['arrTime']+ Fore.RESET])) # 獲取車次站點名稱 row_info.append('/n' + '/n'.join([Fore.GREEN + info['deptStationName'] + Fore.RESET, Fore.RED + info['arrStationName']+ Fore.RESET])) # 獲取車次到達站點所需時間 row_info.append('/n' + info['runTime']) # 獲取票價以及余票信息 seat_price = [] seat_num = [] for seat in info['seatList']: seat_price.append(seat['seatName'] + ':' + seat['seatPrice']) if int(seat['seatNum']) > 10: ticknum = Fore.GREEN + seat['seatNum'] + Fore.RESET else: ticknum = seat['seatNum'] seat_num.append(ticknum) row_info.append('/n'.join(seat_price)) row_info.append('/n'.join(seat_num)) self.qurey_ret.append(row_info) self.qurey_ret.append([' ', ' ', ' ', ' ', ' ', ' ']) return self.qurey_ret def show_with_table(self): ticket_table = prettytable.PrettyTable() ticket_table.field_names = self.header for row in self.qurey_ret: if len(row) == 0: continue ticket_table.add_row(row) return ticket_tabledef main(): arguments = docopt(__doc__) query_args = {} init() # 獲取所有站點信息(stations.txt信息通過 函數獲取) # https: // kyfw.12306.cn / otn / resources / js / framework / station_name.js?station_version = 1.8971 f = open('stations.txt', 'r') info = f.read() stations_info = json.loads(info) # 從所有站點信息中獲取所要查詢站點的代碼信息 query_args['to_station'] = stations_info[arguments['']] query_args['source_station'] = stations_info[arguments['']] query_args['date'] = arguments[''] # 向12306查詢,得到跟車次相關的所有信息 collect_train = CollectInfo() row_ret = collect_train.query_html_ret(query_args) collect_train.paser_ret(row_ret) table = collect_train.show_with_table() print(table) if __name__ == '__main__': main()
新聞熱點
疑難解答