python爬虫实现火车票查询 GUI
时间: 2024-02-29 15:48:47 浏览: 30
根据提供的引用内容,可以使用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网站发送请求并获取火车票信息,然后将结果显示在窗口中的列表框中。