一、相关代码

# @Time: 2024/1/22 20:24# @Author: 马龙强# @File: 实现12306查票购票.py# @software: PyCharm"""网址:https://www.12306.cn/index/数据:车次信息查票链接:https://kyfw.12306.cn/otn/leftTicket/queryE?leftTicketDTO.train_date=2024-01-23&leftTicketDTO.from_station=LON&leftTicketDTO.to_station=XUN&purpose_codes=ADULT"""import requestsfrom pprint import pprintimport json#导入漂亮的制表from prettytable import PrettyTable"""查票功能1.输入出发城市2.输入目的城市3.输入出发时间根据输入城市 -> 通过 city.json 找到对应城市字母(station.json 对应车站)12306自动购票"""#读取json文件f = open('city.json',encoding='utf-8').read()#转成json字典city_data = json.loads(f)# print(city_data)from_city = input('请输入出发的城市:')site_city = input('请输入到达的城市:')from_time = input('请输入出发的时间:')#2024-01-25print('出发城市字母',city_data[from_city])print('目的城市字母',city_data[site_city])"""发送请求:模拟浏览器对于url地址发送请求"""#请求网址headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36","Cookie": "_uab_collina=170592620040439510680099; JSESSIONID=80E55A815952C4C2E5B1AC826CC88FF0; BIGipServerpassport=1005060362.50215.0000; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; route=6f50b51faa11b987e576cdb301e545c4; BIGipServerotn=2095579402.64545.0000; _jc_save_fromStation=%u6F2F%u6CB3%2CLON; _jc_save_toStation=%u4FE1%u9633%2CXUN; _jc_save_fromDate=2024-01-23; _jc_save_toDate=2024-01-22; _jc_save_wfdc_flag=dc"}url = f'https://kyfw.12306.cn/otn/leftTicket/queryE?leftTicketDTO.train_date={from_time}&leftTicketDTO.from_station={city_data[from_city]}&leftTicketDTO.to_station={city_data[site_city]}&purpose_codes=ADULT'#发送请求response = requests.get(url=url,headers=headers)# print(response.json())# print(response.text)json_data = response.json()#实例化一个对象tb = PrettyTable()#设置一个字段名tb.field_names = ['序号','车次','出发时间','到达时间','时长','特等座','一等座','二等座','软卧','硬卧','硬座','无座',]#设置序号page = 1# pprint(json_data)#提取车次信息所在列表result = json_data['data']['result']# pprint(result)#for循环遍历,提取列表里面的元素for i in result:# print(i)#字符串分割 -> index列表index = i.split('|')# print(index)num = index[3]#车次time_1 = index[8] #出发时间time_2 = index[9] #到达时间time_3 = index[10]#时长topGrade = index[32]#特等座first_class = index[31] #一等座second_class = index[30]#二等座hrad_sleeper = index[28]#硬卧hard_seat = index[29] #硬座no_seat = index[26] #无座soft_sleeper = index[23]#软卧dit = {'车次': num,'出发时间': time_1,'到达时间': time_2,'时长': time_3,'特等座': topGrade,'一等座': first_class,'二等座': second_class,'软卧': soft_sleeper,'硬卧': hrad_sleeper,'硬座': hard_seat,'无座': no_seat,}#车次# print(index)# page = 0# for j in index:# print(page,j,sep='****')# page+=1# break#添加字段内容tb.add_row([page,num,time_1,time_2,time_3,topGrade,first_class,second_class,soft_sleeper,hrad_sleeper,hard_seat,no_seat,])# print(dit)page +=1print(tb)

二、结果

三、注意12306城市对应缩写city.json的获取

1.相关链接:12306城市名对应字母缩写 – 悟透 – 博客园 (cnblogs.com)

2.在桌面创建文本文件,复制内容到文本文件中,保存后,更改后缀为.json,放到与代码同级的目录中

四、过程请查看代码注释