周杰伦演唱会门票还能这样抢?看过来!我用Python实现了大麦网自动抢票功能_大麦网抢票有没有黑科技

相信想去周董演唱会的大家都用过大麦网抢票吧?

可是…抢不到啊!!!

该说不说 我抢到了

在这里插入图片描述

那么,今天带大家用Python来制作一个自动抢票的脚本小程序!
知识点:

  • 面向对象编程
  • selenium 操作浏览器
  • pickle 保存和读取Cookie实现免登陆
  • time 做延时操作
  • os 创建文件,判断文件是否存在

开发环境:

  • 版 本:anaconda5.2.0(python3.6.5)
  • 编辑器:pycharm

先导入本次所需的模块

import os  
import time  
import pickle  
from time import sleep  
from selenium import webdriver  

第一步:实现免登录

确定目标,设置全局变量

damai_url = "就是那个网站"  
login_url = "就是那个登陆地址"  
target_url = '就是那个目标网站  
#这里不是我不放,是平台不给放 
#要全部的就来 

初始化加载

class Concert:  
    def \_\_init\_\_(self):  
        self.status = 0           
        self.login_method = 1     
        self.driver = webdriver.Chrome(executable_path='chromedriver.exe')        

登录调用设置cookie

def set\_cookie(self):  
    self.driver.get(damai_url)  
    print("###请点击登录###")  
    while self.driver.title.find('dm-全球演出赛事官方购票平台') != -1:  
        sleep(1)  
    print('###请扫码登录###')  
  
    while self.driver.title != 'dm-全球演出赛事官方购票平台-100%正品、先付先抢、在线选座!':  
       sleep(1)  
    print("###扫码成功###")  
    pickle.dump(self.driver.get_cookies(), open("cookies.pkl", "wb"))  
    print("###Cookie保存成功###")  
    self.driver.get(target_url  

获取cookie

def get\_cookie(self):  
    try:  
        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###')  
    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'):                       
                self.set_cookie()  
            else:  
                self.driver.get(target_url)  
                self.get_cookie()

打开浏览器

def enter\_concert(self):  
    """打开浏览器"""  
    print('###打开浏览器,进入dm网###')  
    
    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("###开始进行日期及票价选择###")  
        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)  
                    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  
            except:  
                print('###未跳转到订单结算界面###')  
            title = self.driver.title  
            if title == '选座购买':  
                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 == '选座购买':  
            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):  
    if self.status in [3,4,5]:  
        print('###开始确认订单###')  
        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('//div[@class = "w1200"]//div[2]//div//div[9]//button[1]').click()  

抢票完成,退出

def finish(self):  


现在能在网上找到很多很多的学习资源,有免费的也有收费的,当我拿到1套比较全的学习资源之前,我并没着急去看第1节,我而是去审视这套资源是否值得学习,有时候也会去问一些学长的意见,如果可以之后,我会对这套学习资源做1个学习计划,我的学习计划主要包括规划图和学习进度表。



分享给大家这份我薅到的免费视频资料,质量还不错,大家可以跟着学习

![](https://img-blog.csdnimg.cn/img_convert/21b2604bd33c4b6713f686ddd3fe5aff.png)



**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
<think>好的,用户想用Python编写自动化脚本演唱会门票。首先,我得回忆一下相关的知识。记得之前看过几个引用,里面提到了Selenium库,还有ChromeDriver的配置。引用[2]和[3]都提到了使用Selenium来实现自动,特别是大麦网的例子。需要确保用户正确安装Python和Selenium,并且配置好浏览器驱动。 用户的问题集中在方法或代码上,所以需要分步骤讲解。首先环境搭建,安装必要的库,比如Selenium,可能还需要处理验证码的问题,但引用中没有详细提到验证码的解决方法,可能需要提醒用户注意这一点,或者使用等待时间和手动介入。 然后,代码结构方面,引用中的示例代码可能包括打开浏览器、登录、选择场次和价,然后下单。需要确保代码示例正确,比如使用WebDriverWait和expected_conditions来等待元素加载,避免因为页面加载慢而找不到元素。 另外,引用[3]提到将ChromeDriver的路径添加到环境变量,或者直接在代码中指定路径。这部分需要明确说明,避免用户运行时出错。 还需要考虑可能的问题,比如时的并发处理,或者如何快速循环检查源。不过根据引用内容,可能只需要基本的自动化操作,不需要太复杂的多线程。 最后,提醒用户法律和道德问题,避免过于频繁的请求导致被封IP,或者违反网站的使用条款。这些在引用中没有提到,但作为负责任的回答,应该包含这些注意事项。 总结回答的结构:环境准备、代码编写步骤、关键点说明、注意事项,最后生成相关问题。确保所有LaTeX格式正确,行内公式用$...$,独立公式用$$...$$,但这个问题可能不需要数学公式,所以可能用不上。不过根据用户给的示例,代码部分需要用代码块,并且引用标识放在相关段落后面。</think>以下是使用Python编写自动脚本的分步指南,结合了Selenium库和主流务平台操作逻辑: ### 一、环境准备 1. 安装Python 3.6+和pip 2. 安装依赖库: ```bash pip install selenium webdriver-manager ``` 3. 配置浏览器驱动(推荐Chrome): ```python from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) ``` ### 二、核心代码实现 ```python 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 # 初始化浏览器 driver = webdriver.Chrome(executable_path="chromedriver路径") driver.get("https://www.damai.cn/") # 以大麦网为例 try: # 登录操作 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, "login-user"))).click() # 输入账号密码(需替换为实际值) driver.find_element(By.ID, "username").send_keys("your_username") driver.find_element(By.ID, "password").send_keys("your_password") driver.find_element(By.CLASS_NAME, "login-btn").click() # 搜索目标演出 search_box = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "search-input"))) search_box.send_keys("周杰伦演唱会") driver.find_element(By.CLASS_NAME, "search-btn").click() # 选择场次和价 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[@class='perform__order__select']//span[text()='选择场次']"))).click() driver.find_element(By.XPATH, "//li[@class='skuname']").click() # 立即购买 driver.find_element(By.XPATH, "//div[@class='buy-link']").click() # 提交订单 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[@class='submit-btn']"))).click() finally: driver.quit() ``` ### 三、关键优化点 1. **智能等待机制**:使用`WebDriverWait`结合`expected_conditions`确保元素加载完成,避免使用固定`sleep`[^3] 2. **多线程监控**:可配合`threading`模块实现多页面监控 ```python import threading def monitor_ticket(url): # 独立监控线程实现 pass ``` 3. **验证码处理**:建议人工介入识别,或使用第三方OCR服务(需注意法律风险) ### 四、注意事项 1. 遵守目标网站的`robots.txt`协议 2. 设置合理的时间间隔(建议≥3秒),避免被封禁IP 3. 提前完成账号登录和收货地址设置 4. 建议在预约前30分钟启动脚本[^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值