自动化抢票的脚本,需通过Selenium库来实现自动化操作。(学习参考)
# 导入必要的库from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport 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"]')))
来源地址:https://blog.csdn.net/weixin_45331480/article/details/129398917