因为我已经足够懒了,只显示了硬卧和硬座的余票信息(毕竟其他票我也没什么购买欲望)。
===========================以上全是扯淡题外话===========================
代码(GitHub地址)中所用到的接口,可以在12306官方新版查询网页中获取到。本文笔者使用了prettytable让显示结果更加美观,使用了json将纯文本的json格式转换成python中的字典数组,在获取数据的时候,使用了User-Agent来模拟浏览器。
代码使用操作方式:
python main.py 2016-06-22 赣州 上海
第一个地址是出发城市,第二个地址是去往的城市。
# encoding:utf-8
import urllib2,os,sys,json,time
from prettytable import PrettyTable
def get_station_list():
f = open('stations.dat')
lines = f.readlines()
dic = {}
for line in lines:
line = line.strip('\n')
dic[line.split(' ')[0]] = line.split(' ')[1]
return dic
def get_content(url):
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'}
req = urllib2.Request(url, None, req_header)
resp = urllib2.urlopen(req,None,30)
content = resp.read()
return content
if __name__=='__main__':
try:
train_date = sys.argv[1]
from_station = get_station_list()[sys.argv[2]]
to_station = get_station_list()[sys.argv[3]]
except:
print 'usage: python main.py 2016-06-22 赣州 南昌'
sys.exit(0)
pass
while 1==1:
os.system('clear')
print '日期:\033[1;32;40m%s\033[0m 从 \033[1;31;40m%s\033[0m 到 \033[1;31;40m%s\033[0m'%(train_date, sys.argv[2], sys.argv[3])
url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date='+train_date+'&leftTicketDTO.from_station='+from_station+'&leftTicketDTO.to_station='+to_station+'&purpose_codes=ADULT'
# print url
content = get_content(url)
j = json.loads(content)
t = PrettyTable(["车次", "出发站", "到达站", "出发时间", "到达时间", "历时", "硬卧", "硬座"])
t.align[u"出发站"] = "l" # Left align city names
t.align[u'到达站'] = 'l'
t.padding_width = 1 # One space between column edges and contents (default)
for item in j['data']:
# item['secretStr'] = ''
if u'无' == item['queryLeftNewDTO']['yz_num']:
item['queryLeftNewDTO']['yz_num'] = ''
if u'无' == item['queryLeftNewDTO']['yw_num']:
item['queryLeftNewDTO']['yw_num'] = ''
t.add_row([
item['queryLeftNewDTO']['station_train_code'],
item['queryLeftNewDTO']['from_station_name'],
item['queryLeftNewDTO']['to_station_name'],
item['queryLeftNewDTO']['start_time'],
item['queryLeftNewDTO']['arrive_time'],
item['queryLeftNewDTO']['lishi'],
item['queryLeftNewDTO']['yw_num'],
item['queryLeftNewDTO']['yz_num']
])
print t
operation = raw_input('')
if 'exit' == operation or 'q' == operation:
sys.exit(0)