程序很簡單,主要是調用了12306的api。用法也很簡單:輸入出發地、目的地、乘車時間,將查詢到的結果在命令行列印出來。對了,這個是我以前參照了:Python3 實現火車票查詢工具_Python_實驗樓 - 實驗樓 ,現在我把簡單修改了一下,適合新人練練手!
有兩點需要注意:
1.from stations import stations這個是stations是個存儲城市和代碼的字典{},譬如南京,對應的城市代碼是NKH,這個就是在stations裡查找得出的。
2.主要用到了colorama,docopt,prettytable可以將命令行的查詢結果以彩色表格形式列印。
3.用到了while True....這樣可以保證程序一直循環,查詢一次,輸出結果以後,再次開始新一輪的查詢。如果需要中斷程序可以用ctrl+c。
使用方法如下:
"""Usage: 輸入要查詢的火車類型可以多選(動車d,高鐵g,特快t,快速k,直達z) 輸入出發地、目的地、出發日期。 查詢結果以命令行形式自動呈現。Examples: Please input the trainType you want to search :dgz Please input the city you want leave :南京 Please input the city you will arrive :北京 Please input the date(Example:2017-09-27) :2018-03-01"""
程序截圖如下:
動態效果如下:
程序原始碼,包含兩部分:1.stations.py 2.searchTrain.py
1.stations.py
import reimport requestsfrom pprint import pprinturl = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9018'requests.packages.urllib3.disable_warnings()#如果不加此句會有:InsecureRequestWarning: Unverified HTTPS request is being madehtml = requests.get(url,verify=False)station = re.findall(u'([\u4e00-\u9fa5]+)\|([A-Z]+)', html.text)stations = dict(station)pprint(stations,indent = 4)
2.searchTrain.py
"""Usage: 輸入要查詢的火車類型可以多選(動車d,高鐵g,特快t,快速k,直達z) 輸入出發地、目的地、出發日期。 查詢結果以命令行形式自動呈現。Examples: Please input the trainType you want to search :dgz Please input the city you want leave :南京 Please input the city you will arrive :北京 Please input the date(Example:2017-09-27) :2018-03-01"""#coding = utf-8#author = Lyon#date = 2017-12-17import jsonimport requestsfrom docopt import docoptfrom prettytable import PrettyTablefrom colorama import init,Forefrom stations import stationsclass searchTrain: def __init__(self): self.trainOption = input('-d動車 -g高鐵 -k快速 -t特快 -z直達,Please input the trainType you want to search :') self.fromStation = input('Please input the city you want leave :') self.toStation = input('Please input the city you will arrive :') self.tripDate = input('Please input the date(Example:2017-09-27) :') self.headers = { "Cookie":"__NRF=74C05F8DA4A54BAD8FE8C1858576401F; JSESSIONID=7F000001F6317B0C83A920B23A62A0D64E27924D83; route=495c805987d0f5c8c84b14f60212447d; BIGipServerotn=602931722.64545.0000; BIGipServerpool_passport=200081930.50215.0000; _jc_save_fromStation=%u4E0A%u6D77%2CSHH; _jc_save_toStation=%u5357%u4EAC%2CNJH; _jc_save_fromDate=2017-07-20; _jc_save_toDate=2017-07-18; _jc_save_wfdc_flag=dc", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", } self.available_trains,self.options = self.searchTrain() @property def trains(self): for item in self.available_trains: cm = item.split('|') train_no = cm[3] initial = train_no[0].lower() if not self.options or initial in self.options: train = [ train_no, '\n'.join([Fore.GREEN + cm[6] + Fore.RESET, Fore.RED + cm[7] + Fore.RESET]), '\n'.join([Fore.GREEN + cm[8] + Fore.RESET, Fore.RED + cm[9] + Fore.RESET]), cm[10], cm[32], cm[25], cm[31], cm[30], cm[21], cm[23], cm[28], cm[24], cm[29], cm[26], cm[22] ] yield train def pretty_print(self): pt = PrettyTable() header = '車次 車站 時間 歷時 商務座 特等座 一等 二等 高級軟臥 軟臥 硬臥 軟座 硬座 無座 其他'.split() pt._set_field_names(header) for train in self.trains: pt.add_row(train) print(pt) def searchTrain(self): arguments = { 'option':self.trainOption, 'from':self.fromStation, 'to':self.toStation, 'date':self.tripDate } options = ''.join([item for item in arguments['option']]) from_station, to_station, date = stations[arguments['from']] , stations[arguments['to']] , arguments['date'] url = ('https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT').format(date,from_station,to_station) requests.packages.urllib3.disable_warnings() html = requests.get(url,headers = self.headers,verify=False) available_trains = html.json()['data']['result'] return available_trains,optionsif __name__ == '__main__': while True: asd = searchTrain() asd.pretty_print()
後續:其實查詢還是很簡單的,就是調用API接口,輸入查詢關鍵詞就OK了,但是要想完整地實現購買火車票的流程,還是一個比較複雜的項目,Github上有完整的項目,喜歡的童鞋可以上去看看~testerSunshine/12306
彩蛋:
下一篇文章:Python命令行實現—查全國7天天氣
下下篇文章:Python—itchat實現微信自動回復
下下下篇文章:Python實現微信查天氣+火車+飛機+快遞!!!