12306车票信息查询
使用Python实现的火车票查询工具:
Usage: ticket.py [-gdtzk] <from> <to> <date>
Options:
-h,--help 帮助信息
-a 所有
-g 高铁
-d 动车
-t 特快
-z 直达
-k 快速
Demo: ticket.py shenzhen beijing 20161001 -g
1 #!/usr/bin/env python 2 #coding:utf-8 3 import urllib2,re,json 4 import ssl,sys,datetime 5 from prettytable import PrettyTable 6 ssl._create_default_https_context = ssl._create_unverified_context #设置SSL为不验证的方式 7 def Parser_station(station_name): #获得站点名对应站点代号的字典 8 url_code="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8966" 9 response=urllib2.urlopen(urllib2.Request(url_code)) 10 result=response.read() 11 stations=re.findall(r'([A-Z]+)\|([a-z]+)',result) 12 stations=dict(stations) 13 stations_dict=dict(zip(stations.values(),stations.keys())) 14 return stations_dict[station_name] 15 16 def Print_ticket(from_station,to_station,select_date,option='-a'): 17 print "旅行计划:\t"+select_date+'\t'+from_station+"\t--->\t"+to_station+"\t"+'[查询时间:\t'+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+']' 18 from_station=Parser_station(from_station) #获得起点的代号 19 to_station=Parser_station(to_station) #获得终点的代号 20 select_date=select_date[0:4]+'-'+select_date[4:6]+'-'+select_date[6:] 21 url_info="https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=%s&from_station=%s&to_station=%s" % (select_date,from_station,to_station) 22 response=urllib2.urlopen(urllib2.Request(url_info)) 23 result=response.read() 24 info=json.loads(result) 25 train_list=info['data']['datas'] 26 pt=PrettyTable() 27 header=["时间",'历时','车次',"站点",'商务座','特等座','一等座','二等座','高级软卧','软卧','硬卧','软座','硬座','无座','其它','备注'] 28 pt.field_names=header 29 tmp=u"正常车次,不受控" 30 num=0 31 option=list(option)[1:] 32 for i in train_list: 33 if i['controlled_train_message'] == tmp: 34 i['controlled_train_message']='' 35 else: 36 pass 37 train_time='\033[92m'+i['start_time']+'\033[0m'+"\n"+'\033[91m'+i['arrive_time']+'\033[0m' 38 train_station='\033[92m'+i['from_station_name']+'\033[0m'+"\n"+'\033[91m'+i['to_station_name']+'\033[0m' 39 li=[train_time,i['lishi'],i['station_train_code'],train_station,i['swz_num'],i['tz_num'],i['zy_num'],i['ze_num'],i['gr_num'],i['rw_num'],i['yw_num'],i['rz_num'],i['yz_num'],i['wz_num'],i['qt_num'],i['controlled_train_message']] 40 train_code=str(i['station_train_code'][0]).lower() 41 if train_code in option: 42 pt.add_row(li) 43 num+=1 44 elif 'h' in option: 45 print ''' 46 Usage: ticket.py [-gdtzk] <from> <to> <date> 47 Options: 48 -h,--help 帮助信息 49 -a 所有 50 -g 高铁 51 -d 动车 52 -t 特快 53 -z 直达 54 -k 快速 55 Example: 56 ticket.py shenzhen beijing 20161001 -g 57 ''' 58 return 0 59 elif 'a' in option: 60 pt.add_row(li) 61 num+=1 62 else: 63 pass 64 print pt 65 print "Total: ",num 66 if len(sys.argv) < 5: 67 Print_ticket(sys.argv[1],sys.argv[2],sys.argv[3]) 68 else: 69 Print_ticket(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])