大麦网selenium半自动抢票

抢票前注意事项


一、在抢票之前,用户还得提前做好以下几项准备工作,保证抢票手速快:
1. 需要提前登录大麦账号
2. 需要手动选座

环境准备

# 我下载的1.12版本的
chromedriver.exe

# selenium模块
pip install selenium -i https://mirrors.aliyun.com/pypi/simple/

脚本

import os
import time
import pickle
from time import sleep
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions

# 大麦网主页
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.search_category.0.0.aa637b68TAI1Si&id=716759481923&clicktitle=%E4%BA%94%E6%9C%88%E5%A4%A92023%E5%A5%BD%E5%A5%BD%E5%A5%BD%E6%83%B3%E8%A7%81%E5%88%B0%E4%BD%A0%E5%8C%97%E4%BA%AC%E6%BC%94%E5%94%B1%E4%BC%9A0'

# target_url = 'https://detail.damai.cn/item.htm?spm=a2oeg.home.card_0.ditem_1.327523e19Uw7jp&id=714266271400'


def InitChorm():
    """
    这样不会被检测到是用的selenium
    :return:
    """
    options = ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)

    driver = Chrome(options=options)
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
        Object.defineProperty(navigator, 'webdriver', {
          get: () => undefined
        })
      """
    })
    return driver


class Concert:
    def __init__(self):
        self.status = 0  # 状态,表示如今进行到何种程度
        self.login_method = 1  # {0:模拟登录,1:Cookie登录}自行选择登录方式
        # self.driver = webdriver.Chrome(executable_path='chromedriver.exe')  # 默认Chrome浏览器
        self.driver = InitChorm()  # 默认Chrome浏览器

    def set_cookie(self):
        self.driver.get(damai_url)
        print("请登录")
        # 检测是否登录
        while 1:
            try:
                self.driver.find_element_by_xpath("/html/body/div[2]/div/div[3]/div[1]/div[1]/span")
                time.sleep(1)
            except Exception:
                break
        while 1:
            try:
                self.driver.find_element_by_xpath("/html/body/div[2]/div/div[3]/div[1]/a[2]/div")
                break
            except Exception:
                continue

        pickle.dump(self.driver.get_cookies(), open("cookies.pkl", "wb"))
        print("###Cookie保存成功###")
        self.driver.get(target_url)

    def get_cookie(self):
        try:
            cookies = pickle.load(open("cookies.pkl", "rb"))  # 载入cookie
            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###')
        except Exception as e:
            print(e)

    def login(self):
        if self.login_method == 0:
            self.driver.get(login_url)
            # 载入登录界面
            print('###开始登录###')

        elif self.login_method == 1:
            if not os.path.exists('cookies.pkl'):
                # 如果不存在cookie.pkl,就获取一下
                self.set_cookie()
            else:
                self.driver.get(target_url)
                self.get_cookie()

    def enter_concert(self):
        """打开浏览器"""
        print('###打开浏览器,进入大麦网###')
        self.driver.maximize_window()  # 最大化窗口
        # 调用登陆
        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 isElementExist(self, element):
        flag = True
        browser = self.driver
        try:
            browser.find_element_by_xpath(element)
            return flag

        except:
            flag = False
            return flag

    def choose_ticket(self):
        if self.status == 2:  # 登录成功入口
            print("=" * 30)
            print("###开始进行日期及票价选择###")
            first_while = 1
            second_while = 1
            thired_while = 1
            while first_while:
                while 1:
                    try:
                        result = self.driver.find_element_by_xpath('/html/body/div[2]/div/div[1]/div[1]/div/div[2]/div[5]/div[1]/div[1]')
                        self.driver.refresh()
                    except Exception:
                        break
                # while second_while:  # 如果跳转到了订单结算界面就算这步成功了,否则继续执行此步
                #     try:
                #         buybutton = self.driver.find_element_by_class_name('buybtn').text
                #         if buybutton == "提交开售提醒":
                #             # 改变现有状态
                #             self.status = 2
                #             self.driver.refresh()  # 刷新页面
                #             time.sleep(1)
                #             print('###抢票未开始,刷新等待开始###')
                #             continue
                #         elif buybutton == "立即预定":
                #             self.driver.find_element_by_class_name('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
                #         else:
                #             break
                #     except:
                #         print('###已经开始抢票了###')
                #         break
                while thired_while:
                    try:
                        self.driver.find_element_by_xpath(
                            "/html/body/div[2]/div/div[1]/div[1]/div/div[2]/div[4]/div[7]/div/div[1]")
                        # 点击该按钮
                        self.driver.find_element_by_class_name("buy-link").click()
                    except Exception:
                        thired_while = 0
                        second_while = 1
                title = self.driver.title
                if title == '选择座位':
                    print("选择座位")
                    # 实现选座位购买的逻辑
                    # self.choice_seats()
                # elif title == '确认订单':
                #     while True:
                #         # 如果标题为确认订单
                #         print('waiting ......')
                #         if self.isElementExist('//*[@id="container"]/div/div[9]/button'):
                #             self.check_order()
                #             break

    def choice_seats(self):
        while self.driver.title == '选择座位':
            try:
                while self.driver.find_element_by_xpath('//*[@id="app"]/div/div[4]/div[2]/button'):
                    print('请快速的选择您的座位!!!')
            except Exception:
                break
        while self.driver.title == "订单确认页":
            time.sleep(1)
            self.driver.find_element_by_css_selector(
                '#dmOrderSubmitBlock_DmOrderSubmitBlock > div:nth-child(2) > div > div:nth-child(2) > div:nth-child(3) > div:nth-child(2)').click()
            try:
                time.sleep(1)
                self.driver.find_element_by_xpath('//*[@id="confirm"]/div/div[2]/div[2]').click()
            except Exception:
                continue
        # while self.driver.title == "支付宝付款":
        #     time.sleep(1)
        #     self.driver.find_element_by_xpath('//*[@id="app"]/div[3]/div[1]/button[2]').click()
        #     time.sleep(0.5)
        #     self.driver.find_element_by_xpath('//*[@id="app"]/div[3]/div/div[1]/div[2]/input').send_keys('17600059660')
        #     self.driver.find_element_by_xpath('//*[@id="app"]/div[3]/div/button').click()

    def finish(self):
        self.driver.quit()


if __name__ == '__main__':
    con = Concert()  # 具体如果填写请查看类中的初始化函数
    try:
        con.enter_concert()  # 打开浏览器
        con.choose_ticket()  # 开始抢票
    except Exception as e:
        con.finish()

selenium版本高的代码

import os
import time
import pickle
from time import sleep
from selenium import webdriver
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions

# 大麦网主页
from selenium.webdriver.common.by import By

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.search_category.0.0.aa637b68TAI1Si&id=716759481923&clicktitle=%E4%BA%94%E6%9C%88%E5%A4%A92023%E5%A5%BD%E5%A5%BD%E5%A5%BD%E6%83%B3%E8%A7%81%E5%88%B0%E4%BD%A0%E5%8C%97%E4%BA%AC%E6%BC%94%E5%94%B1%E4%BC%9A0'

# target_url = 'https://detail.damai.cn/item.htm?spm=a2oeg.home.card_0.ditem_1.327523e19Uw7jp&id=714266271400'


def InitChorm():
    """
    这样不会被检测到是用的selenium
    :return:
    """
    options = ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)

    driver = Chrome(options=options)
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
        Object.defineProperty(navigator, 'webdriver', {
          get: () => undefined
        })
      """
    })
    return driver


class Concert:
    def __init__(self):
        self.status = 0  # 状态,表示如今进行到何种程度
        self.login_method = 1  # {0:模拟登录,1:Cookie登录}自行选择登录方式
        # self.driver = webdriver.Chrome(executable_path='chromedriver.exe')  # 默认Chrome浏览器
        self.driver = InitChorm()  # 默认Chrome浏览器
    def set_cookie(self):
        self.driver.get(damai_url)
        print("请登录")
        # 检测是否登录
        while 1:
            try:
                self.driver.find_element(By.XPATH,"/html/body/div[2]/div/div[3]/div[1]/div[1]/span")
                time.sleep(1)
            except Exception:
                break
        while 1:
            try:
                self.driver.find_element(By.XPATH,"/html/body/div[2]/div/div[3]/div[1]/a[2]/div")
                break
            except Exception:
                continue

        pickle.dump(self.driver.get_cookies(), open("cookies.pkl", "wb"))
        print("###Cookie保存成功###")
        self.driver.get(target_url)

    def get_cookie(self):
        try:
            cookies = pickle.load(open("cookies.pkl", "rb"))  # 载入cookie
            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###')
        except Exception as e:
            print(e)

    def login(self):
        if self.login_method == 0:
            self.driver.get(login_url)
            # 载入登录界面
            print('###开始登录###')

        elif self.login_method == 1:
            if not os.path.exists('cookies.pkl'):
                # 如果不存在cookie.pkl,就获取一下
                self.set_cookie()
            else:
                self.driver.get(target_url)
                self.get_cookie()

    def enter_concert(self):
        """打开浏览器"""
        print('###打开浏览器,进入大麦网###')
        self.driver.maximize_window()  # 最大化窗口
        # 调用登陆
        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 isElementExist(self, element):
        flag = True
        browser = self.driver
        try:
            browser.find_element(By.XPATH,element)
            return flag

        except:
            flag = False
            return flag

    def choose_ticket(self):
        if self.status == 2:  # 登录成功入口
            print("=" * 30)
            print("###开始进行日期及票价选择###")
            first_while = 1
            second_while = 1
            thired_while = 1
            while first_while:
                while 1:
                    try:
                        result = self.driver.find_element(By.XPATH,'/html/body/div[2]/div/div[1]/div[1]/div/div[2]/div[5]/div[1]/div[1]')
                        self.driver.refresh()
                        # print(self.driver.find_element(By.XPATH,'/html/body/div[2]/div/div[1]/div[1]/div/div[2]/div[6]/div[1]/div[2]').text)
                    except Exception:
                        break
                # while second_while:  # 如果跳转到了订单结算界面就算这步成功了,否则继续执行此步
                #     try:
                #         buybutton = self.driver.find_element_by_class_name('buybtn').text
                #         if buybutton == "提交开售提醒":
                #             # 改变现有状态
                #             self.status = 2
                #             self.driver.refresh()  # 刷新页面
                #             time.sleep(1)
                #             print('###抢票未开始,刷新等待开始###')
                #             continue
                #         elif buybutton == "立即预定":
                #             self.driver.find_element_by_class_name('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
                #         else:
                #             break
                #     except:
                #         print('###已经开始抢票了###')
                #         break
                while thired_while:
                    try:
                        self.driver.find_element(By.XPATH,
                            "/html/body/div[2]/div/div[1]/div[1]/div/div[2]/div[4]/div[7]/div/div[1]")
                        # 点击该按钮
                        self.driver.find_element(By.CLASS_NAME,"buy-link").click()
                    except Exception:
                        thired_while = 0
                        second_while = 1
                title = self.driver.title
                if title == '选择座位':
                    print("选择座位")
                    # 实现选座位购买的逻辑
                    # self.choice_seats()
                # elif title == '确认订单':
                #     while True:
                #         # 如果标题为确认订单
                #         print('waiting ......')
                #         if self.isElementExist('//*[@id="container"]/div/div[9]/button'):
                #             self.check_order()
                #             break

    def choice_seats(self):
        while self.driver.title == '选择座位':
            try:
                while self.driver.find_element(By.XPATH,'//*[@id="app"]/div/div[4]/div[2]/button'):
                    print('请快速的选择您的座位!!!')
            except Exception:
                break
        while self.driver.title == "订单确认页":
            time.sleep(1)
            self.driver.find_element(By.CSS_SELECTOR,
                '#dmOrderSubmitBlock_DmOrderSubmitBlock > div:nth-child(2) > div > div:nth-child(2) > div:nth-child(3) > div:nth-child(2)').click()
            try:
                time.sleep(1)
                self.driver.find_element(By.XPATH,'//*[@id="confirm"]/div/div[2]/div[2]').click()
            except Exception:
                continue
        # while self.driver.title == "支付宝付款":
        #     time.sleep(1)
        #     self.driver.find_element_by_xpath('//*[@id="app"]/div[3]/div[1]/button[2]').click()
        #     time.sleep(0.5)
        #     self.driver.find_element_by_xpath('//*[@id="app"]/div[3]/div/div[1]/div[2]/input').send_keys('17600059660')
        #     self.driver.find_element_by_xpath('//*[@id="app"]/div[3]/div/button').click()

    def finish(self):
        self.driver.quit()


if __name__ == '__main__':
    con = Concert()  # 具体如果填写请查看类中的初始化函数
    # try:
    con.enter_concert()  # 打开浏览器
    con.choose_ticket()  # 开始抢票
    # except Exception as e:
    #     con.finish()


posted @   河图s  阅读(1201)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
历史上的今天:
2020-05-08 vue.js(1)
抢票前注意事项环境准备脚本selenium版本高的代码
点击右上角即可分享
微信分享提示