首先导入本文需要加载的库,如果你有些库还没有安装,导致运行代码时报错,可以在Anaconda Prompt中用pip方法安装。
本文应用到的库较少,只应用了requests,prettytable和json。
源码和city.json
百度网盘
链接:https://pan.baidu.com/s/1XLyhBesxTnezgQTKb1jG8g?pwd=1314
提取码:1314
源码如下:
import requests
import prettytable as pt
import json
start_city=input('输入出发城市:')
end_city=input('输入目的城市:')
date=input('输入出发时间<2022-01-01>:')
#读取city文件
f=open('city.json',encoding='utf-8')
city_json=json.loads(f.read())
print(city_json)
from_station=city_json[start_city]
to_station=city_json[end_city]
print(from_station,to_station)
#确定url
url=f'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={date}&leftTicketDTO.from_station={from_station}&leftTicketDTO.to_station={to_station}&purpose_codes=ADULT'
#模拟浏览器
headers={
'Cookie': '_uab_collina=165979152311352067672312; JSESSIONID=F05E6CAF8FB5FA68B7FF1622085A67DE; tk=EJH1AFQfUsrxp-GfjBaIVDFT2ph4gU0Vija1a0; RAIL_EXPIRATION=1660082139967; RAIL_DEVICEID=CTpeGfikJEtDnod54kTGTMq7qoBlylMfAFWlU4kCAikIfMclrhqKnieYjJI3weJQXHBKoqaikSg2AHnkWNuI7mtYlcaau0_MPS5bTT49GMogS-lxznCcP1n-VT2_yDigjh9wwVl6VUnbp6raTFucbGN3cNmNrsda; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; _jc_save_wfdc_flag=dc; _jc_save_toDate=2022-08-07; _jc_save_fromStation=%u516D%u5B89%2CUAH; _jc_save_toStation=%u5408%u80A5%2CHFH; BIGipServerpool_passport=149160458.50215.0000; route=9036359bb8a8a461c164a04f8f50b252; BIGipServerotn=82838026.50210.0000; uKey=2a9de11d7c8c2d6a501724bacdacbdb642671d03efe3a9acbb81998759c2dabd; fo=ow5s5l2mxuort55frTnEwwS1reg2iFIRmc_HS9fPsmoTjioPN6Tj-9pESRElKZ1P_8d-kpgFseYIY5es-_tFjVRdGBvn8nfEleF-0rfLzwTAvcpdVzkFM224sfY5glf9nRQkQJKHcSWY6u3uKmpLgTUcFQpPeztJVWM1zyi8NeRHTU8PgRr2O6ApWJA; current_captcha_type=Z; _jc_save_fromDate=2022-08-08',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
#发送请求
response=requests.get(url=url,headers=headers)
#2.获取数据,获取服务器返回响应数据 print(response.json())
#实例化对象
tb=pt.PrettyTable()
tb.field_names=[
'序号',
'出发城市',
'到达城市',
'车次',
'出发时间',
'到达时间',
'耗时',
'特等座',
'一等',
'二等',
'软卧',
'硬卧',
'硬座',
'无座',
]
#序号
page=0
#3.解析数据获取response.json()
for index in response.json()['data']['result']:
#index.split('|')
content_list=index.split('|')
num=content_list[3] #车次
star_time=content_list[8] #出发时间
end_time=content_list[9] #到达时间
use_time=content_list[10] #耗时
topGrade=content_list[25] #特等座
if topGrade:
pass
else:
topGrade=content_list[32]
first_class=content_list[30] #一等
second_class=content_list[31] #二等
hard_sleeper=content_list[28] #硬卧
hard_seat=content_list[29] #硬座
no_seat=content_list[26] #无座
soft_sleeper=content_list[23] #软卧
dit={
'车次':num,
'出发时间':star_time,
'达到时间':end_time,
'耗时':use_time,
'特等座':topGrade,
'一等':first_class,
'二等':second_class,
'软卧':soft_sleeper,
'硬卧':hard_sleeper,
'硬座':hard_seat,
'无座':no_seat,
}
tb.add_row([
page,
start_city,
end_city,
num,
star_time,
end_time,
use_time,
topGrade,
first_class,
second_class,
soft_sleeper,
hard_sleeper,
hard_seat,
no_seat,
])
page+=1
print(tb)
|