Building a Command-Line Train Ticket Query Tool with Python
This tutorial explains how to create a Python CLI application named tickets that parses command-line arguments, retrieves station codes, queries the 12306 railway API for ticket data, and displays the results in a formatted table using libraries such as docopt, requests, and prettytable.
This tutorial guides you through creating a Python command‑line application named tickets that queries Chinese railway ticket information from the 12306 website.
First, design the CLI syntax: $ tickets [-gdtkz] <from> <to> <date> , where options select train types (high‑speed, bullet, etc.).
Set up a virtual environment with virtualenv -p /usr/bin/python3 venv and activate it using . venv/bin/activate .
Install docopt to parse arguments, and write a docstring defining usage; then call docopt(__doc__) inside the cli() function to obtain the parsed parameters.
Extract station codes by downloading https://kyfw.12306.cn/otn/resources/js/framework/station_name.js , parsing it with a regular expression in parse.py , and saving the mapping as stations.py :
# coding: utf-8
import re
from pprint import pprint
with open('stations.html', 'r') as f:
text = f.read()
stations = re.findall(u'([\u4e00-\u9fa5]+)\|([A-Z]+)', text)
pprint(dict(stations), indent=4)Build the request URL using the user‑provided date and station codes, then fetch JSON data with requests.get(url, verify=False) :
import requests
url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format(date, from_station, to_station)
r = requests.get(url, verify=False)
data = r.json()Process the returned JSON to obtain the list of train rows and format the output with prettytable for a readable table of train number, times, and seat availability:
from prettytable import PrettyTable
headers = '车次 车站 时间 历时 商务 一等 二等 软卧 硬卧 软座 硬座 无座'.split()
pt = PrettyTable()
pt.field_names = headers
for row in data['data']['datas']:
# extract needed fields and add to table
pt.add_row([...])
print(pt)The complete source code is available at https://github.com/protream/tickets .
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.