火车票车票查询-Python

本文介绍了如何使用Python的requests库实现12306网站的查票购票功能,包括读取城市缩写信息、用户输入查询参数并发送请求获取车次详情。
摘要由CSDN通过智能技术生成

一、相关代码

# @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 requests
from pprint import pprint
import 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-25
print('出发城市字母',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 +=1

print(tb)

二、结果

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

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

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

四、过程请查看代码注释

 

  • 60
    点赞
  • 73
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
根据提供的引用内容,可以使用Python编写爬虫程序来实现火车票查询GUI。以下是一个简单的示例代码: ```python import requests from bs4 import BeautifulSoup import tkinter as tk def search_train(): # 获取用户输入出发站和到达站 start_station = start_entry.get() end_station = end_entry.get() # 构造请求URL url = f"https://www.12306.cn/index/otn/leftTicket/query?leftTicketDTO.train_date=2022-01-01&leftTicketDTO.from_station={start_station}&leftTicketDTO.to_station={end_station}&purpose_codes=ADULT" # 发送请求并获取响应 response = requests.get(url) data = response.json() # 解析响应数据 train_list = data['data']['result'] # 清空结果列表 result_listbox.delete(0, tk.END) # 将火车票信息添加到结果列表 for train in train_list: result_listbox.insert(tk.END, train) # 创建GUI窗口 window = tk.Tk() window.title("火车票查询") window.geometry("400x300") # 创建标签和输入框 start_label = tk.Label(window, text="出发站:") start_label.pack() start_entry = tk.Entry(window) start_entry.pack() end_label = tk.Label(window, text="到达站:") end_label.pack() end_entry = tk.Entry(window) end_entry.pack() # 创建查询按钮 search_button = tk.Button(window, text="查询", command=search_train) search_button.pack() # 创建结果列表 result_listbox = tk.Listbox(window) result_listbox.pack() # 运行GUI窗口 window.mainloop() ``` 这段代码使用了requests库发送HTTP请求,使用BeautifulSoup库解析HTML响应,使用tkinter库创建GUI窗口。用户可以在窗口中输入出发站和到达站,点击查询按钮后,程序会向12306网站发送请求并获取火车票信息,然后将结果显示在窗口中的列表框中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马龙强_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值