如何使用python抢火车票

使用 python 抢火车票可提高成功率。获取车次信息:通过 requests 库发送 GET 请求获取车次信息。实时查询车票:循环发送 GET 请求查询车票,若有票打印车次信息。自动下单:循环查询车票并自动下单,若有票则拼接下单参数发送 POST 请求下单。

如何使用python抢火车票

如何使用 Python 抢火车票

介绍

抢火车票一直是一项艰巨的任务,尤其是热门线路和节假日出行高峰期。Python 作为一门强大的编程语言,可以自动化抢票过程,提高抢票成功率。

所需工具

  • Python 3.6 或更高版本
  • requests 库
  • beautifulsoup4 库

步骤

1. 获取车次信息

import requests
from bs4 import BeautifulSoup

# 设置请求头,模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
}

# 发送请求获取车次信息
url = 'https://kyfw.12306.cn/otn/resources/js/query/train_list.js'
response = requests.get(url, headers=headers)

# 解析车次信息
soup = BeautifulSoup(response.text, 'lxml')
trains = soup.select('script')[-1].text

2. 实时查询车票

import time

# 设置查询参数
from_station = '北京'
to_station = '上海'
train_date = '2023-05-01'

while True:
    # 发送请求查询车票
    url = 'https://kyfw.12306.cn/otn/leftTicket/query?' + 'leftTicketDTO.train_date=' + train_date + '&leftTicketDTO.from_station=' + from_station + '&leftTicketDTO.to_station=' + to_station + '&purpose_codes=ADULT'
    response = requests.get(url, headers=headers)

    # 解析车票信息
    soup = BeautifulSoup(response.text, 'lxml')
    tickets = soup.find_all('tr')

    # 筛选出有票的车次
    available_trains = []
    for ticket in tickets:
        if ticket.find('td', {'id': 'ticket'}) is not None:
            available_trains.append(ticket)

    # 打印有票车次
    if len(available_trains) > 0:
        for train in available_trains:
            print('车次:{},出发站:{},到达站:{},出发时间:{},到达时间:{},剩余票数:{}'.format(
                train.find('td', {'id': 'train_no'}).text,
                train.find('td', {'id': 'from_station_name'}).text,
                train.find('td', {'id': 'to_station_name'}).text,
                train.find('td', {'id': 'start_time'}).text,
                train.find('td', {'id': 'arrive_time'}).text,
                train.find('td', {'id': 'ticket'}).text
            ))
            break
    else:
        print('暂无余票,继续查询...')

    # 间隔一段时间再查询
    time.sleep(1)

3. 自动下单

import time

# 设置抢票参数
seat_type = 'O'  # 座位类型(O:二等座,M:一等座)
passenger_name = '张三'  # 乘客姓名
passenger_id = '身份证号'  # 乘客身份证号
phone_number = '12345678910'  # 乘客手机号

# 循环查询车票并自动下单
while True:
    # 发送请求查询车票
    url = 'https://kyfw.12306.cn/otn/leftTicket/query?' + 'leftTicketDTO.train_date=' + train_date + '&leftTicketDTO.from_station=' + from_station + '&leftTicketDTO.to_station=' + to_station + '&purpose_codes=ADULT'
    response = requests.get(url, headers=headers)

    # 解析车票信息
    soup = BeautifulSoup(response.text, 'lxml')
    tickets = soup.find_all('tr')

    # 筛选出有票的车次
    available_trains = []
    for ticket in tickets:
        if ticket.find('td', {'id': 'ticket'}) is not None:
            available_trains.append(ticket)

    # 自动下单
    if len(available_trains) > 0:
        train = available_trains[0]
        seat_count = train.find('td', {'id': 'ticket'}).text  # 获取剩余票数

        if int(seat_count) >= 1:
            # 拼接下单参数
            data = {
                'secretStr': train.find('form', {'id': 'form_submit'})['action'],
                'train_date': train_date,
                'back_train_date': train_date,
                'tour_flag': 'dc',
                'purpose_codes': 'ADULT',
                'query_from_station_name': from_station,
                'query_to_station_name': to_station,
                'undefined': '',
                'from_station': from_station,
                'to_station': to_station,
                'seat_types': seat_type,
                'train_no': train.find('td', {'id': 'train_no'}).text,
                'stationTrainCode': train.find('td', {'id': 'station_train_code'}).text,
                'leftTicket': seat_count,
                'submitToken': train.find('input', {'id': 'submitToken'})['value'],
                'passengerTicketStr': passenger_name + ',1,' + seat_type + ',' + passenger_id + ',' + 'N' + ',11,' + phone_number,
                'oldPassengerStr': passenger_name + ',' + passenger_id + ',' + '11'
            }

            # 发送下单请求
            url = 'https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest'
            response = requests.post(url, data=data, headers=headers)
            print(response.text)  # 打印下单结果

            break
    else:
        print('暂无余票,继续查询...')

    # 间隔一段时间再查询
    time.sleep(1)

以上就是如何使用python抢火车票的详细内容,更多请关注其它相关文章!