PHP前端开发

12306抢票python代码

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

如何使用 Python 代码抢 12306 火车票?

1. 导入必要的库

import timeimport requestsfrom lxml import etree

2. 获取票务信息

# 设置目标车次和出行日期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)

3. 解析 HTML 响应

立即学习“Python免费学习笔记(深入)”;

# 解析 HTML 响应,提取票务信息html_parser = etree.HTML(response.text)train_info_list = html_parser.xpath('//tr[@id]')

4. 筛选符合条件的车次

# 根据车次号筛选符合条件的车次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

5. 提交抢票请求

# 获取可抢票的座位类型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