import re
import requests
def keys_values(d, value):
return list(d.keys())[list(d.values()).index(value)]
headers = {
"Cookie":
"_uab_collina=169692832736292006740293; tk=J8HeHzkZevrt4pki7lrzlw0gWQAuAtETriqaAQ09x1x0; JSESSIONID=80DA6DCEEB3A7FDC280CBA5EB4ADE8EF; BIGipServerpassport=887619850.50215.0000; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; BIGipServerotn=2715222282.64545.0000; route=6f50b51faa11b987e576cdb301e545c4; fo=gjqtmqmmol0d2hzzRpUJYAaa5wjGg2oatrbfhoM8xQHWmqPOWzLy_3UnUqS_i1tWRHqXXkEe4JBlsGFqlBbgWaUjIiW_idy872Dqx4dACVfEHEP0rB-_1cFO30Pd_bMtLxpghhUtHTLVNTfo8cwMj-MxUf9bPD_s-azl6vQZoNgeWFsEY2U_Uqf7AZs; _jc_save_fromDate=2023-10-10; _jc_save_toDate=2023-10-10; _jc_save_wfdc_flag=dc; _jc_save_fromStation=%u6B66%u6C49%2CWHN; _jc_save_toStation=%u6DF1%u5733%u5317%2CIOQ",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",
"X-Requested-With":"XMLHttpRequest"
}
station_url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?"
station_param = {"station_version":"1.9278"}
res = requests.get(url=station_url,headers=headers,params=station_param).text
find_city =re.findall(r'@.*?\|(.*?)\|',res)
find_city_id =re.findall(r'@.*?\|.*?\|(.*?)\|',res)
city_dic = {}
for c,i in zip(find_city,find_city_id):
city_dic[c] = i
url= "https://kyfw.12306.cn/otn/leftTicket/queryZ?"
from_station = "深圳北"
to_station = "武汉"
from_station = city_dic[from_station]
to_station = city_dic[to_station]
params={
"leftTicketDTO.train_date": "2023-10-11",
"leftTicketDTO.from_station": from_station,
"leftTicketDTO.to_station": to_station,
"purpose_codes": "ADULT",
}
res = requests.get(url=url,headers=headers,params=params).json()
data_list = res['data']['result']
header_list = ['车次','起始站','出发时间','到达时间','历史','商务座','一等座','二等座','软卧','硬卧','硬座','无座']
# print(data_list)
print(header_list)
for data in data_list:
all_data_list = data.split('|')
from_s = list(city_dic.keys())[list(city_dic.values()).index(all_data_list[6])]
to_s = list(city_dic.keys())[list(city_dic.values()).index(all_data_list[7])]
train_msg = [
all_data_list[3],
f"{from_s}-{to_s}",
all_data_list[8],
all_data_list[9],
all_data_list[10],
all_data_list[32] if all_data_list[32] != "" else "--",
all_data_list[31] if all_data_list[31] != "" else "--",
all_data_list[30] if all_data_list[30] != "" else "--",
all_data_list[23] if all_data_list[23] != "" else "--",
all_data_list[28] if all_data_list[28] != "" else "--",
all_data_list[29] if all_data_list[29] != "" else "--",
all_data_list[26] if all_data_list[26] != "" else "--",
all_data_list[1] if all_data_list[1] != "" else "--",
]
print(train_msg)
获取到的结果如下: