python抢票12306火车票代码
时间: 2023-12-23 19:28:26 浏览: 140
以下是一个简单的Python抢票12306火车票的代码示例:
```python
import requests
def query_tickets(date, from_station, to_station):
url = "https://kyfw.12306.cn/otn/leftTicket/queryZ"
params = {
"leftTicketDTO.train_date": date,
"leftTicketDTO.from_station": from_station,
"leftTicketDTO.to_station": to_station,
"purpose_codes": "ADULT"
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
}
response = requests.get(url, params=params, headers=headers)
data = response.json()
tickets = data["data"]["result"]
for ticket in tickets:
print(ticket)
# 示例使用
query_tickets("2022-01-01", "BJP", "SHH")
```
该代码使用了requests库发送HTTP请求,模拟了12306官网的查询接口,可以根据指定的日期、出发站和到达站查询火车票信息。其中,`date`参数表示日期,格式为"YYYY-MM-DD";`from_station`参数表示出发站的编码;`to_station`参数表示到达站的编码。代码会打印出查询到的火车票信息。
阅读全文