用python预约抢火车票
使用 python 编写脚本来自动预约抢票,提高抢票成功率。步骤包括:安装必要库、获取火车信息、编写抢票脚本(包括乘客信息、循环刷新查询、提交订单、支付订单)和运行脚本。
用 Python 抢火车票
使用 Python 编写脚本来自动预约抢票可以大大提高抢票成功率。
核心步骤:
- 安装必要的库。获取火车信息。编写抢票脚本。运行脚本。
具体步骤:
1. 安装必要的库
pip install requests beautifulsoup4
2. 获取火车信息
import requestsfrom bs4 import BeautifulSoup# 车站代号from_station = ‘BJ’to_station = ‘SH’# 出发日期date = ‘2023-03-01’url = f’kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={date}&leftTicketDTO.from_station={from_station}&leftTicketDTO.to_station={to_station}&purpose_codes=ADULT’response = requests.get(url)
3. 编写抢票脚本
from time import sleep# 乘客信息passengers = [‘张三’, ‘李四’]while True: response = requests.get(url) soup = BeautifulSoup(response.text, ‘html.parser’) tickets = soup.find_all(‘tr’, class_=’ticket’) for ticket in tickets: if ticket.find(‘td’, class_=’checkbox’) and ‘有’ in ticket.text:seat_type = ticket.find(‘td’, class_=’seat-type’).texttrain_no = ticket.find(‘td’, class_=’train-no’).textsecret_str = ticket.find(‘td’, class_=’secret-str’).textprint(f’抢到票了: {seat_type} {train_no}’)# 提交订单order_url = ‘kyfw.12306.cn/otn/leftTicket/submitOrderRequest’data = { ‘secretStr’: secret_str, ‘train_date’: date, ‘back_train_date’: date, ‘tour_flag’: ‘dc’, ‘purpose_codes’: ‘ADULT’, ‘query_from_station_name’: from_station, ‘query_to_station_name’: to_station, ‘undefined’: ”}order_response = requests.post(order_url, data=data)# 支付订单pay_url = order_response.json()[‘result’][‘submitUrl’]pay_response = requests.get(pay_url)print(f’支付链接: {pay_url}’)# 成功抢票,退出循环break sleep(1)
4. 运行脚本
在 Python 命令行中运行脚本:
python抢票脚本.py
提醒:
脚本会不断刷新查询页面,直到抢到票。抢票成功后,脚本会打印支付链接,需要手动打开支付页面完成支付。由于抢票难度较大,无法保证每次都能成功。
以上就是用python预约抢火车票的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » 用python预约抢火车票