Operations 11 min read

Step-by-Step Guide to Using Python Selenium for 12306 Train Ticket Booking

This tutorial shows programmers how to set up a Python Selenium script on Windows to automatically log in, select stations, choose travel dates, and purchase train tickets from the 12306 website during the Spring Festival rush, including all required code snippets and configuration details.

High Availability Architecture
High Availability Architecture
High Availability Architecture
Step-by-Step Guide to Using Python Selenium for 12306 Train Ticket Booking

Introduction: The article explains how programmers can use Python and Selenium to automate the process of purchasing train tickets on China's 12306 platform during the Spring Festival travel rush.

Environment: It requires Windows 8.1, Python 3.6.1, Firefox browser, and the geckodriver executable, which should be placed alongside python.exe or in the Firefox directory and added to PATH.

Import Modules: The script imports webdriver, Keys, time, Select, By, WebDriverWait, and expected_conditions from Selenium.

from selenium import webdriver      # control browser
from selenium.webdriver.common.keys import Keys  # send keys
import time   # time module
from selenium.webdriver.support.select import Select  # handle dropdown
from selenium.webdriver.common.by import By   # locate elements
from selenium.webdriver.support.ui import WebDriverWait  # explicit wait
from selenium.webdriver.support import expected_conditions as EC  # wait conditions

Login Module: The script launches Firefox, opens the 12306 login page, fills in username and password, waits for the captcha, and clicks the login button, handling possible captcha refresh.

browser = webdriver.Firefox()
browser.get("https://kyfw.12306.cn/otn/login/init")
browser.find_element_by_id('username').clear()
browser.find_element_by_id('username').send_keys('xxxxx')
browser.find_element_by_id('password').send_keys('xxxxx')
time.sleep(10)  # wait for captcha
try:
    browser.find_element_by_id('loginSub').click()
except:
    browser.find_element_by_class_name('touclick-bgimg touclick-reload touclick-reload-normal').click()
    time.sleep(20)
    browser.find_element_by_id('loginSub').click()

Navigation Module: After login, the script navigates to the ticket reservation page, sets departure and arrival stations by executing JavaScript to modify hidden input values, removes the readonly attribute from the date field, and inputs the desired travel date.

clickReserve = browser.find_element_by_link_text('车票预订').click()
jsf = 'var a = document.getElementById("fromStation");a.value = "BJP"'
browser.execute_script(jsf)
jst = 'var a = document.getElementById("toStation");a.value = "LZJ"'
browser.execute_script(jst)
js = "document.getElementById('train_date').removeAttribute('readonly')"
browser.execute_script(js)
browser.find_element_by_id('train_date').clear()
browser.find_element_by_id('train_date').send_keys('2018-02-01')
browser.find_element_by_id('query_ticket').click()

Ticket Purchase: The script waits until the target train ID appears, clicks the reservation button, selects a passenger, chooses a seat type, and submits the order, handling possible waiting for the final confirmation button.

start_time = "Thu Jan 04 08:00:00 2018"
b = time.mktime(time.strptime(start_time,"%a %b %d %H:%M:%S %Y"))
a = float(b)-time.time()
time.sleep(a)
WebDriverWait(browser,10).until(EC.presence_of_element_located((By.ID, "ticket_2400000Z550L")))
ticket = browser.find_element_by_xpath('//tr[@id="ticket_2400000Z550L"]/td[13]/a').click()
# select passenger
WebDriverWait(browser,10).until(EC.presence_of_element_located((By.ID, "normalPassenger_8")))
browser.find_element_by_id('normalPassenger_8').click()
s = Select(browser.find_element_by_id('seatType_1'))
s.select_by_value('6')  # advanced soft sleeper
browser.find_element_by_id('submitOrder_id').click()
WebDriverWait(browser,10).until(EC.presence_of_element_located((By.ID, "qr_submit_id")))
browser.find_element_by_link_text('提交订单')
browser.find_element_by_id('qr_submit_id').click()

Summary and Tips: Users must replace placeholders such as username, password, station values, travel date, and XPath for the desired train; the script works faster than manual booking but should be used for technical exchange only, not for scalping.

PythonSeleniumscriptWeb Automationticket-booking12306
High Availability Architecture
Written by

High Availability Architecture

Official account for High Availability Architecture.

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.