使用python脚本实现查询火车票信息的效果图如下:
实现的代码:
1 # coding: utf-8 2 3 """命令行火车票查看器 4 5 Usage: 6 tickets [-gdtkz] 7 8 Options: 9 -h,--help 显示帮助菜单 10 -g 高铁 11 -d 动车 12 -t 特快 13 -k 快速 14 -z 直达 15 16 Example: 17 tickets 北京 上海 2016-10-10 18 tickets -dg 成都 南京 2016-10-10 19 """ 20 21 import json 22 import requests 23 import prettytable 24 from docopt import docopt 25 from colorama import init, Fore 26 27 28 class CollectInfo: 29 def __init__(self): 30 self.qurey_ret = [] 31 self.header = ['车次信息', '发/到时间', '发/到站', '历时', '票价', '余票'] 32 33 # 获取车次相关的所有信息 34 def query_html_ret(self, query_args): 35 url = 'http://api.12306.com/v1/train/trainInfos?arrStationCode={to_station}&deptDate={date} 36 &deptStationCode={source_station}&findGD=false'.format(to_station=query_args['to_station'], 37 source_station=query_args['source_station'], 38 date=query_args['date']) 39 row_ret = requests.get(url) 40 return row_ret.json() 41 42 # 解析获取到的结果 43 def paser_ret(self, row_ret): 44 trains_info = row_ret['data']['trainInfos'] 45 for info in trains_info: 46 row_info = [] 47 # 获取车次信息 48 row_info.append(' ' + info['trainCode']) 49 50 # 获取车次到站时间信息 51 row_info.append(' ' + ' '.join([Fore.GREEN + info['deptTime']+ Fore.RESET, 52 Fore.RED + info['arrTime']+ Fore.RESET])) 53 54 # 获取车次站点名称 55 row_info.append(' ' + ' '.join([Fore.GREEN + info['deptStationName'] + Fore.RESET, 56 Fore.RED + info['arrStationName']+ Fore.RESET])) 57 58 # 获取车次到达站点所需时间 59 row_info.append(' ' + info['runTime']) 60 61 # 获取票价以及余票信息 62 seat_price = [] 63 seat_num = [] 64 for seat in info['seatList']: 65 seat_price.append(seat['seatName'] + ':' + seat['seatPrice']) 66 if int(seat['seatNum']) > 10: 67 ticknum = Fore.GREEN + seat['seatNum'] + Fore.RESET 68 else: 69 ticknum = seat['seatNum'] 70 seat_num.append(ticknum) 71 row_info.append(' '.join(seat_price)) 72 row_info.append(' '.join(seat_num)) 73 self.qurey_ret.append(row_info) 74 self.qurey_ret.append([' ', ' ', ' ', ' ', ' ', ' ']) 75 76 return self.qurey_ret 77 78 def show_with_table(self): 79 ticket_table = prettytable.PrettyTable() 80 81 ticket_table.field_names = self.header 82 83 for row in self.qurey_ret: 84 if len(row) == 0: 85 continue 86 ticket_table.add_row(row) 87 return ticket_table 88 89 90 def main(): 91 arguments = docopt(__doc__) 92 query_args = {} 93 init() 94 95 # 获取所有站点信息(stations.txt信息通过 函数获取) 96 # https: // kyfw.12306.cn / otn / resources / js / framework / station_name.js?station_version = 1.8971 97 f = open('stations.txt', 'r') 98 info = f.read() 99 stations_info = json.loads(info) 100 101 # 从所有站点信息中获取所要查询站点的代码信息 102 query_args['to_station'] = stations_info[arguments['']] 103 query_args['source_station'] = stations_info[arguments['']] 104 query_args['date'] = arguments[''] 105 106 # 向12306查询,得到跟车次相关的所有信息 107 collect_train = CollectInfo() 108 row_ret = collect_train.query_html_ret(query_args) 109 110 collect_train.paser_ret(row_ret) 111 table = collect_train.show_with_table() 112 print(table) 113 114 115 if __name__ == '__main__': 116 main()