Build a Python CLI to Fetch 12306 Train Tickets in Seconds

This tutorial walks you through creating a Python command‑line tool named “tickets” that, using virtualenv, docopt, and prettytable, retrieves real‑time train ticket information from China’s 12306 service by specifying departure, destination, and date, and displays the results in a formatted table.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Python CLI to Fetch 12306 Train Tickets in Seconds

Everyone has used the 12306 website; this guide shows how to write a Python program that returns train ticket information from the command line.

1. Interface Design

The small application is called tickets . Users only need to provide a departure station, a destination station, and a date. Example usage: $ tickets from to date With optional flags, e.g.:

$ tickets -gdtkz from to date

2. Development Environment

Create an isolated Python 3 environment with virtualenv and activate it:

$ virtualenv -p /usr/bin/python3 venv
$ . venv/bin/activate

3. Argument Parsing

Use the docopt library for simple command‑line parsing. Install it first:

$ pip3 install docopt
docopt

reads the usage pattern defined in the script’s docstring and extracts the arguments automatically.

4. Fetching Data

Query the 12306 API with a URL such as:

https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-07-01&from_station=SHH&to_station=BJP

Station codes are obtained from the JavaScript file station_name.js and saved locally as stations.html for lookup.

5. Displaying Results

Install prettytable to format the output like a MySQL table: $ pip3 install prettytable The final output shows the train schedule in a neatly aligned table.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CLIdocoptprettytableweb-scraping
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.