自动化抢票的脚本,需通过Selenium库来实现自动化操作。(学习参考)
# 导入必要的库
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# 设置浏览器参数
options = webdriver.ChromeOptions()
options.add_argument("--incognito")
options.add_argument("--start-maximized")
# 创建浏览器对象
browser = webdriver.Chrome(options=options)
# 访问大麦网登录页面
browser.get('https://passport.damai.cn/login?ru=https%3A%2F%2Fwww.damai.cn%2F')
# 等待登录页面加载完成
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="login-title"]')))
# 输入账号密码并点击登录
username = 'your_username' # 替换为自己的账号
password = 'your_password' # 替换为自己的密码
browser.find_element_by_xpath('//input[@name="username"]').send_keys(username)
browser.find_element_by_xpath('//input[@name="password"]').send_keys(password)
browser.find_element_by_xpath('//button[text()="登录"]').click()
# 等待登录成功并跳转到抢票页面
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="page__title"]')))
browser.get('https://detail.damai.cn/item.htm?id=123456') # 替换为自己要抢票的演出链接
# 等待抢票页面加载完成
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="buybtn"]')))
# 开始不断刷新页面,直到出现“立即购买”按钮
while True:
try:
browser.refresh()
buy_btn = browser.find_element_by_xpath('//div[@class="buybtn"]')
if buy_btn.text == '立即购买':
break
except:
pass
time.sleep(1)
# 点击“立即购买”按钮
buy_btn.click()
# 等待选择票框加载完成
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="select_right"]')))
# 选择票框、票价和数量(这里只选择一张最便宜的票)
browser.find_element_by_xpath('//span[text()="选择票框"]').click()
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//ul[@class="perform__select__list"]')))
select_list = browser.find_elements_by_xpath('//ul[@class="perform__select__list"]//li')
select_list[0].click()
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//span[@class="select_right_list_content_price_text"]')))
select_price = browser.find_elements_by_xpath('//span[@class="select_right_list_content_price_text"]')[0]
select_price.click()
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class
下面是注释
# 初始化浏览器
browser = webdriver.Chrome()
# 找到包含选项的元素列表
select_list = browser.find_elements_by_xpath('//ul[@class="perform__select__list"]//li')
# 点击第一个选项
select_list[0].click()
# 等待价格元素出现
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//span[@class="select_right_list_content_price_text"]')))
# 找到价格元素
select_price = browser.find_elements_by_xpath('//span[@class="select_right_list_content_price_text"]')[0]
# 点击价格元素
select_price.click()
# 等待某个元素出现
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="some_class"]')))