Operations 4 min read

How to Build a Python Bot to Snatch 12306 Train Tickets

This guide explains how to use Python and the Splinter library to automate login, search, and booking on China’s 12306 railway website, covering required tools, key URLs, control identification, cookie extraction, and running the script while noting the remaining captcha step.

Efficient Ops
Efficient Ops
Efficient Ops
How to Build a Python Bot to Snatch 12306 Train Tickets

Many people use ticket‑snatching apps for China’s 12306 railway, but few understand how they work. This article demonstrates a simple Python implementation that automates the whole process.

Prepare Tools

12306 account (username and password)

Python

Chrome browser and matching chromedriver

Download the script from https://github.com/ppy2790/tickets

Underlying Principle

The script uses Splinter , an open‑source Python web‑testing tool, to drive a browser, interact with page elements, and collect results automatically.

Key URLs

Search page: https://kyfw.12306.cn/otn/leftTicket/init

Login page: https://kyfw.12306.cn/otn/login/init

My 12306 page: https://kyfw.12306.cn/otn/index/initMy12306

Booking confirmation: https://kyfw.12306.cn/otn/confirmPassenger/initDc

Finding Control Names

Use Chrome’s developer tools (F12) to locate the names of the username, password, and departure‑city fields. The departure city value is stored in a cookie, which can be extracted from the Network → Cookies panel.

After copying the cookie values for several common cities, store them in a Python dictionary.

Ticket Query Code

The script opens the search URL, fills in the controls with the extracted values, and sends the request to query available tickets.

Running the Bot

Execute the Python script; the browser will automatically perform login, search, and booking steps. The only manual interaction required is solving the 12306 captcha and confirming payment after a ticket is secured.

This content is reproduced from the public account “Computer and Network Security” for technical discussion only.
PythonWeb Automation12306SplinterTicket Scraping
Efficient Ops
Written by

Efficient Ops

This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.

0 followers
Reader feedback

How this landed with the community

login 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.