12306火车票抢票Python代码步骤如下:1. 导入库并获取票务信息;2. 解析HTML响应并提取票务信息;3. 根据车次号筛选符合条件的车次;4. 获取可抢票的座位类型;5. 设置抢票间隔并提交抢票请求,直至抢票成功。

如何使用 Python 代码抢 12306 火车票?
1. 导入必要的库
<code class="python">import time import requests from lxml import etree</code>
2. 获取票务信息
<code class="python"># 设置目标车次和出行日期
train_num = 'G6102'
date = '2023-04-19'
# 发送查询请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
}
url = f'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={date}&leftTicketDTO.from_station=BJP&leftTicketDTO.to_station=GZH&purpose_codes=ADULT'
response = requests.get(url, headers=headers)</code>3. 解析 HTML 响应
立即学习“Python免费学习笔记(深入)”;
<code class="python"># 解析 HTML 响应,提取票务信息
html_parser = etree.HTML(response.text)
train_info_list = html_parser.xpath('//tr[@id]')</code>4. 筛选符合条件的车次
<code class="python"># 根据车次号筛选符合条件的车次
for train_info in train_info_list:
if train_info.xpath('./td[1]/text()')[0] == train_num:
seat_type_list = train_info.xpath('./td[@seat_types]')
break</code>5. 提交抢票请求
<code class="python"># 获取可抢票的座位类型
seat_types = []
for seat_type in seat_type_list:
if seat_type.xpath('./@class')[0] == 'btn btn-primary-disabled':
continue
else:
seat_types.append(seat_type.xpath('./@id')[0])
# 提交抢票请求
while True:
# 设置抢票间隔
time.sleep(0.5)
# 提交抢票请求
form_data = {
'secretStr': '',
'train_date': date,
'back_train_date': date,
'tour_flag': 'dc',
'purpose_codes': 'ADULT',
'query_from_station_name': '北京',
'query_to_station_name': '广州',
'undefined': ''
}
for seat_type in seat_types:
form_data[seat_type] = ''
response = requests.post('https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest', data=form_data, headers=headers)
# 判断是否抢票成功
if response.json()['status'] == True:
print('抢票成功,订单已生成!')
break</code>以上就是12306抢票python代码的详细内容,更多请关注php中文网其它相关文章!
铁路12306是一款由中铁程科技有限责任公司官方发行推出的购票订票软件。这款软件能够帮助用户随时随地查询火车高铁的信息,不管是想要购票还是退票改签都可以在这里进行操作,有需要的小伙伴快来保存下载体验吧!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号