Python实例题:Python3实现火车票查询工具

目录

Python实例题

题目

python3-train-ticket-queryPython 3 火车票查询工具脚本

代码解释

get_station_code 函数:

query_train_tickets 函数:

主程序:

运行思路

注意事项

Python实例题

题目

Python3实现火车票查询工具

python3-train-ticket-queryPython 3 火车票查询工具脚本

import requests
import json


def get_station_code():
    """
    获取车站代码映射字典
    """
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9163'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        data = response.text
        stations = data.split('@')[1:]
        station_code_dict = {}
        for station in stations:
            parts = station.split('|')
            station_name = parts[1]
            station_code = parts[2]
            station_code_dict[station_name] = station_code
        return station_code_dict
    except requests.RequestException as e:
        print(f"请求出错: {e}")
        return {}


def query_train_tickets(from_station, to_station, date):
    """
    查询火车票信息
    :param from_station: 出发站名称
    :param to_station: 到达站名称
    :param date: 出发日期,格式:YYYY-MM-DD
    """
    station_code_dict = get_station_code()
    if from_station not in station_code_dict or to_station not in station_code_dict:
        print("未找到车站信息,请检查输入。")
        return
    from_code = station_code_dict[from_station]
    to_code = station_code_dict[to_station]
    url = f'https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date={date}&leftTicketDTO.from_station={from_code}&leftTicketDTO.to_station={to_code}&purpose_codes=ADULT'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init'
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        result = response.json()
        if result['status']:
            trains = result['data']['result']
            for train in trains:
                info = train.split('|')
                train_number = info[3]
                start_station = info[6]
                end_station = info[7]
                start_time = info[8]
                end_time = info[9]
                duration = info[10]
                # 二等座余票信息
                second_seat = info[30] if info[30] else '无'
                print(f"车次: {train_number}, 出发站: {start_station}, 到达站: {end_station}, "
                      f"出发时间: {start_time}, 到达时间: {end_time}, 历时: {duration}, 二等座余票: {second_seat}")
        else:
            print("查询失败,请稍后重试。")
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except json.JSONDecodeError:
        print("数据解析出错,请稍后重试。")


if __name__ == "__main__":
    from_station = input("请输入出发站名称: ")
    to_station = input("请输入到达站名称: ")
    date = input("请输入出发日期(格式:YYYY-MM-DD): ")
    query_train_tickets(from_station, to_station, date)
    

代码解释

  • get_station_code 函数

    • 发送请求获取 12306 车站代码的 JavaScript 文件。
    • 解析该文件,提取车站名称和对应的代码,存储在字典中返回。
  • query_train_tickets 函数

    • 调用 get_station_code 函数获取车站代码字典。
    • 根据用户输入的出发站、到达站和日期,构造查询车票信息的 URL。
    • 发送请求获取车票信息的 JSON 数据。
    • 若查询成功,解析 JSON 数据,提取车次、出发站、到达站、出发时间、到达时间、历时和二等座余票信息并打印。
  • 主程序

    • 提示用户输入出发站名称、到达站名称和出发日期。
    • 调用 query_train_tickets 函数进行车票查询。

运行思路

  • 安装依赖库:确保已经安装了 requests 库,若未安装,可使用以下命令进行安装:
pip install requests
  • 运行脚本:将上述代码保存为 train_ticket_query.py 文件,在终端中运行:
python train_ticket_query.py
  • 输入信息:按照提示输入出发站名称、到达站名称和出发日期。
  • 查看结果:程序会打印出查询到的火车票信息。

注意事项

  • 反爬机制:12306 有严格的反爬机制,可能会出现请求失败、验证码等问题,可考虑使用代理 IP、设置请求间隔等方式应对。
  • 合法性:确保遵守 12306 的相关规定,不要进行恶意刷票等违规操作。
  • 数据更新:车站代码可能会更新,可定期更新代码中的车站代码获取逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值