Python 自动抢火车票教程:安装 requests 和 BeautifulSoup4 库。获取火车信息,包括车次、出发/到达站、日期等。根据需求筛选候选车次,如有剩余车票。构造请求头,模拟浏览器发送请求。使用多线程或多进程并发抢票,增加成功率。

Python 自动抢火车票教程
一、安装必要的库
二、获取火车信息
<code class="python">import requests from bs4 import BeautifulSoup url = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2023-03-01&leftTicketDTO.from_station=GZQ&leftTicketDTO.to_station=BJP&leftTicketDTO.purpose_codes=ADULT' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')</code>
三、筛选候选车次
立即学习“Python免费学习笔记(深入)”;
根据自己的需求,从页面中筛选出候选车次。
<code class="python"># 获取所有车次信息
trains = soup.find_all('tr', {'class': 'train'})
# 筛选候选车次
candidate_trains = []
for train in trains:
if train.find('td', {'class': 'rest_tickets'}): # 有剩余车票
candidate_trains.append(train)</code>四、构造请求头
设置请求头,模拟浏览器发送请求。
<code class="python">headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.119 Safari/537.36 Edg/109.0.1518.71'
}</code>五、自动抢票
使用多线程或多进程并发抢票,增加成功率。
<code class="python">import threading
import time
def搶票(train):
# 构造抢票请求数据
data = {
'secretStr': train.find('input', {'name': 'secretStr'})['value'],
'train_date': train.find('input', {'name': 'train_date'})['value'],
'back_train_date': '',
'tour_flag': 'dc',
'purpose_codes': 'ADULT',
'query_from_station_name': '广州',
'query_to_station_name': '北京',
'controlled_train_flag': '0'
}
# 发送抢票请求
response = requests.post('https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest', data=data, headers=headers)
# 处理抢票结果
if response.json()['status'] == True:
print(f'抢票成功!车次:{train.find("a", {"target": "_blank"}).text.strip()}')
else:
print('抢票失败!')
# 多线程抢票
threads = []
for train in candidate_trains:
thread = threading.Thread(target=搶票, args=(train,))
threads.append(thread)
for thread in threads:
thread.start()
# 等待线程结束
for thread in threads:
thread.join()</code>以上就是python自动抢火车票教程的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号