通过 ticket-booking 库(示例):
python
from ticket_booking import TrainTicket
# 初始化查询
train = TrainTicket()
# 查询火车票
result = train.search(
from_station="北京",
to_station="上海",
date="2024-01-20"
)
# 显示结果
for ticket in result:
print(f"车次: {ticket['train_no']}")
print(f"出发时间: {ticket['departure_time']}")
print(f"到达时间: {ticket['arrival_time']}")
print(f"座位类型: {ticket['seat_type']}")
print(f"价格: {ticket['price']}")
print("-" * 30)
- 调用12306官方API(需要验证)
python
import requests
import json
from datetime import datetime
def query_train_tickets(from_station, to_station, date):
"""
查询火车票信息
"""
# 12306 API地址(注意:官方API经常变化,需要处理验证)
url = "https://kyfw.12306.cn/otn/leftTicket/query"
params = {
'leftTicketDTO.train_date': date,
'leftTicketDTO.from_station': from_station,
'leftTicketDTO.to_station': to_station,
'purpose_codes': 'ADULT'
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init'
}
try:
response = requests.get(url, params=params, headers=headers, verify=False)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"查询失败: {e}")
return None
# 使用示例
if __name__ == "__main__":
# 需要先获取车站代码
result = query_train_tickets("BJP", "SHH", "2024-01-20")
if result:
print(json.dumps(result, indent=2, ensure_ascii=False))
- 使用第三方API服务
python
import requests
import pandas as pd
def query_via_third_party(from_city, to_city, date):
"""
使用聚合数据等第三方API
需要申请API Key
"""
api_key = "your_api_key_here"
url = f"http://apis.juhe.cn/train/station2s"
params = {
"from": from_city,
"to": to_city,
"date": date,
"key": api_key,
"dtype": "json"
}
response = requests.get(url, params=params)
data = response.json()
if data["error_code"] == 0:
trains = data["result"]["list"]
df = pd.DataFrame(trains)
return df[['train_no', 'start_time', 'arrive_time', 'lishi', 'seat_types']]
else:
print(f"查询失败: {data['reason']}")
return None
- 完整的命令行工具示例
python
import argparse
import requests
from prettytable import PrettyTable
from colorama import init, Fore
init(autoreset=True)
class TrainQuery:
def __init__(self):
self.stations = self.load_stations()
def load_stations(self):
"""加载车站代码"""
# 这里可以从文件或API加载车站代码对照表
stations = {
"北京": "BJP",
"上海": "SHH",
"广州": "GZQ",
"深圳": "SZQ",
"南京": "NJH",
"杭州": "HZH"
}
return stations
def query(self, from_city, to_city, date):
"""查询车票"""
from_code = self.stations.get(from_city)
to_code = self.stations.get(to_city)
if not from_code or not to_code:
print("车站名称错误")
return
# 这里调用查询API
print(f"查询 {from_city} → {to_city} {date} 的车次...")
# 模拟数据
trains = [
{"车次": "G1", "出发": "08:00", "到达": "12:30", "历时": "4.5h", "商务座": "有", "一等座": "有", "二等座": "有"},
{"车次": "G3", "出发": "10:00", "到达": "14:30", "历时": "4.5h", "商务座": "有", "一等座": "有", "二等座": "无"},
{"车次": "D305", "出发": "12:30", "到达": "18:00", "历时": "5.5h", "商务座": "无", "一等座": "有", "二等座": "有"},
]
# 用表格显示
table = PrettyTable()
table.field_names = ["车次", "出发时间", "到达时间", "历时", "商务座", "一等座", "二等座"]
for train in trains:
row = [
Fore.GREEN + train["车次"],
train["出发"],
train["到达"],
train["历时"],
Fore.GREEN + "有" if train["商务座"] == "有" else Fore.RED + "无",
Fore.GREEN + "有" if train["一等座"] == "有" else Fore.RED + "无",
Fore.GREEN + "有" if train["二等座"] == "有" else Fore.RED + "无"
]
table.add_row(row)
print(table)
def main():
parser = argparse.ArgumentParser(description="火车票查询工具")
parser.add_argument("-f", "--from", dest="from_city", required=True, help="出发城市")
parser.add_argument("-t", "--to", dest="to_city", required=True, help="到达城市")
parser.add_argument("-d", "--date", required=True, help="出发日期 (格式: YYYY-MM-DD)")
args = parser.parse_args()
query_tool = TrainQuery()
query_tool.query(args.from_city, args.to_city, args.date)
if __name__ == "__main__":
main()