Python Selenium Ticket Purchasing Automation Guide
This article provides a step‑by‑step tutorial on setting up Python and Selenium, installing the appropriate browser driver, and writing a script to automate ticket purchasing on a web platform, including code examples, execution flow, and practical tips for handling different site structures.
Before starting, ensure Python and an IDE such as PyCharm are installed; you can follow previous introductory articles for installation instructions.
Install the Selenium library using the command pip install selenium , then download the matching ChromeDriver from the official site and add its executable path to your system’s environment variables.
Create a new .py file and use the following script as a base for automating ticket purchases on Damai (the example site). The script demonstrates how to load cookies for login, navigate to the ticket page, handle pop‑ups, select tickets, choose seats, and finally submit the order.
<code>import os # create folder, check file existence
import time # timing utilities
import pickle # save/load cookies for login bypass
from time import sleep
from selenium import webdriver # browser automation
from selenium.webdriver.common.by import By
"""
1. Implement login‑free access
2. Automate ticket selection and order submission
"""
damai_url = 'https://www.damai.cn/'
login_url = 'https://passport.damai.cn/login?ru=https%3A%2F%2Fwww.damai.cn%2F'
target_url = 'https://detail.damai.cn/item.htm?spm=a2oeg.home.card_0.ditem_2.591b23e1AyXdAl&id=729700971838'
class Concert:
def __init__(self):
self.status = 0
self.login_method = 1 # 0: simulate login, 1: cookie login
self.driver = webdriver.Chrome(executable_path='chromedriver.exe')
def set_cookies(self):
"""Save login cookies"""
self.driver.get(damai_url)
print('###请点击登录###')
while self.driver.title.find('大麦网-全球演出赛事官方购票平台') != -1:
sleep(1)
print('###请扫码登录###')
while self.driver.title != '大麦网-全球演出赛事官方购票平台-100%正品、先付先抢、在线选座!':
sleep(1)
print('###扫码成功###')
pickle.dump(self.driver.get_cookies(), open('cookies.pkl', 'wb'))
print('###cookie保存成功###')
self.driver.get(target_url)
def get_cookie(self):
"""Load saved cookies"""
cookies = pickle.load(open('cookies.pkl', 'rb'))
for cookie in cookies:
cookie_dict = {
'domain': '.damai.cn',
'name': cookie.get('name'),
'value': cookie.get('value')
}
self.driver.add_cookie(cookie_dict)
print('###载入cookie###')
def login(self):
"""Perform login based on selected method"""
if self.login_method == 0:
self.driver.get(login_url)
print('###开始登录###')
elif self.login_method == 1:
if not os.path.exists('cookies.pkl'):
self.set_cookies()
else:
self.driver.get(target_url)
self.get_cookie()
def enter_concert(self):
"""Open browser and navigate to the ticket page"""
print('###打开浏览器,进入大麦网###')
self.login()
self.driver.refresh()
self.status = 2
print('###登录成功###')
if self.isElementExist('/html/body/div[2]/div[2]/div/div/div[3]/div[2]'):
self.driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div/div/div[3]/div[2]').click()
def choose_ticket(self):
"""Select ticket and proceed to order"""
if self.status == 2:
print('=' * 30)
print('###开始进行日期及票价选择###')
while self.driver.title.find('确认订单') == -1:
try:
buybutton = self.driver.find_element(By.CLASS_NAME, 'buybtn').text
if buybutton == '提交缺货登记':
self.status = 2
self.driver.get(target_url)
elif buybutton == '立即预定':
self.driver.find_element('buybtn').click()
self.status = 3
elif buybutton == '立即购买':
self.driver.find_element(By.CLASS_NAME, 'buybtn').click()
self.status = 4
elif buybutton == '选座购买':
self.driver.find_element(By.CLASS_NAME, 'buybtn').click()
self.status = 5
except:
print('###没有跳转到订单结算界面###')
title = self.driver.title
if title == '选座购买':
self.choice_seats()
elif title == '确认订单':
while True:
print('正在加载.......')
if self.isElementExist('//*[@id="container"]/div/div[9]/button'):
self.check_order()
break
def choice_seats(self):
"""Select seats when required"""
while self.driver.title == '选座购买':
while self.isElementExist('//*[@id="app"]/div[2]/div[2]/div[1]/div[2]/img'):
print('请快速选择你想要的座位!!!')
while self.isElementExist('//*[@id="app"]/div[2]/div[2]/div[2]/div'):
self.driver.find_element(By.XPATH, '//*[@id="app"]/div[2]/div[2]/div[2]/button').click()
def check_order(self):
"""Finalize the order"""
if self.status in [3, 4, 5]:
print('###开始确认订单###')
time.sleep(1)
try:
self.driver.find_element(By.XPATH, '//*[@id="container"]/div/div[2]/div[2]/div[1]/div/label').click()
except Exception as e:
print('###购票人信息选中失败, 自行查看元素位置###')
print(e)
time.sleep(0.5)
self.driver.find_element(By.XPATH, '//*[@id="container"]/div/div[9]/button').click()
time.sleep(20)
def isElementExist(self, element):
"""Check if an element exists"""
try:
self.driver.find_element(By.XPATH, element)
return True
except:
return False
def finish(self):
"""Close the browser after completion"""
self.driver.quit()
if __name__ == '__main__':
con = Concert()
try:
con.enter_concert()
con.choose_ticket()
except Exception as e:
print(e)
con.finish()
</code>Different ticketing websites may have varying page structures, so you might need to adjust element locators and interaction logic accordingly; Selenium also supports headless mode to run the browser without a UI, which can save resources.
At the end of the article, a QR code is provided for readers to obtain a free Python public‑course package containing e‑books, tutorials, project examples, and source code.
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.