PYTHON实现12306余票查询-2018年3月7日有效

时间:2022-02-03 22:51:23
 

先开看下实现结果:

PYTHON实现12306余票查询-2018年3月7日有效

源码:

from prettytable import PrettyTable
import re,time,requests,json

with open(r'D:\PycharmProjects\12306\StationLib.txt', encoding='utf-8') as fp:
    patt = re.compile('\d+')
    data = patt.sub('',fp.read())

list = re.findall(r'\d*@.+?(?=@)',data)
AreaLib = {}
AreaLib_Converse = {}
for i in list:
    area = re.search(r'[\u4e00-\u9fa5]+',i)
    code = re.search(r'(?<=[^\x00-\xff]\|)\w+(?=\|)',i)
    AreaLib[area.group()] = code.group()
    AreaLib_Converse[code.group()] = area.group()

try:
    from_station = AreaLib[input('出发地>:')]
    to_station = AreaLib[input('目的地>:')]
except KeyError:
    print('地址不存在!')
    exit()
train_date = input('出发时间(8位,默认今天)>:')
train_date1 = '{}-{}-{}'.format(train_date[0:4],train_date[4:6],train_date[6:8])
if train_date == '':
    train_date1 = time.strftime('%Y-%m-%d', time.localtime())
url = "https://kyfw.12306.cn/otn/leftTicket/queryO?" \
      "leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}" \
      "&purpose_codes=ADULT".format(train_date1,from_station,to_station)
wb_data = requests.get(url)
origindata = json.loads(wb_data.text)

table = PrettyTable(["出发站","到达站","班次", "出发时间","到达时间","历时","V商务","V一等","V二等","软卧","硬卧","软座","硬座","无座"])
for i in origindata['data']['result']:
    basedata = i.split('|')
    train_name = basedata[3]
    start_station = AreaLib_Converse[basedata[6]]
    end_station = AreaLib_Converse[basedata[7]]
    train_start = basedata[8]
    train_end = basedata[9]
    train_duration = basedata[10]
    Gte = basedata[25]
    Gyi = basedata[31]
    Ger = basedata[30]
    Kruanwo = basedata[23]
    Kyingwo = basedata[28]
    Kruanzuo = basedata[24]
    Kyingzuo = basedata[29]
    Kwuzuo = basedata[26]
    table.add_row([start_station,end_station,train_name,train_start,train_end,train_duration,Gte,Gyi,Ger,Kruanwo,Kyingwo,Kruanzuo,Kyingzuo,Kwuzuo])
print(table)
最后,本代码依赖一个本地的车站代码对照表,对照表内容可以从‘https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9049’获取,复制下来存到txt直接能用。