为了顺利买到演唱会的票用Python制作了自动抢票的脚本


Posted in Python onOctober 16, 2021

知识点:

  • 面向对象编程
  • 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 = "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.77f24d15RWgT4o&id=654534889506&clicktitle=%E5%A4%A7%E4%BC%97%E7

初始化加载

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

登录调用设置cookie

def set_cookie(self):
    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)

获取cookie

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("###开始进行日期及票价选择###")
        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'):
                # 座位手动选择 选中座位之后//*[@id="app"]/div[2]/div[2]/div[1]/div[2]/img 就会消失
                print('请快速的选择您的座位!!!')
            # 消失之后就会出现 //*[@id="app"]/div[2]/div[2]/div[2]/div
            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):
    self.driver.quit()

测试代码是否成功

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

    except Exception as e:
        print(e)
        con.finish()

最后看下效果如何

为了顺利买到演唱会的票用Python制作了自动抢票的脚本

到此这篇关于为了顺利买到演唱会的票用Python制作了自动抢票的脚本的文章就介绍到这了,更多相关Python 自动抢票内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
在主机商的共享服务器上部署Django站点的方法
Jul 22 Python
Pandas 同元素多列去重的实例
Jul 03 Python
Python并发之多进程的方法实例代码
Aug 15 Python
python修改txt文件中的某一项方法
Dec 29 Python
python使用PyQt5的简单方法
Feb 27 Python
Django实现文件上传和下载功能
Oct 06 Python
浅析python内置模块collections
Nov 15 Python
Python 使用type来定义类的实现
Nov 19 Python
Python面向对象封装操作案例详解
Dec 31 Python
python 进程池pool使用详解
Oct 15 Python
python中threading和queue库实现多线程编程
Feb 06 Python
 python中的元类metaclass详情
May 30 Python
Python 游戏大作炫酷机甲闯关游戏爆肝数千行代码实现案例进阶
Python实现老照片修复之上色小技巧
Python anaconda安装库命令详解
Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析
Python爬虫入门案例之爬取二手房源数据
Python爬虫入门案例之回车桌面壁纸网美女图片采集
Python Django模型详解
You might like
DC最新动画电影:《战争之子》为何内容偏激,毁了一个不错的漫画
2020/04/09 欧美动漫
php调用Google translate_tts api实现代码
2013/08/07 PHP
php的sso单点登录实现方法
2015/01/08 PHP
CodeIgniter多语言实现方法详解
2016/01/20 PHP
zend framework重定向方法小结
2016/05/28 PHP
php+javascript实现的动态显示服务器运行程序进度条功能示例
2017/08/07 PHP
php打开本地exe程序,js打开本地exe应用程序,并传递相关参数方法
2018/02/06 PHP
拖动Html元素集合 Drag and Drop any item
2006/12/22 Javascript
javascript 面向对象全新理练之继承与多态
2009/12/03 Javascript
node.js中的events.emitter.listeners方法使用说明
2014/12/10 Javascript
jQuery点击按钮弹出遮罩层且内容居中特效
2015/12/14 Javascript
javascript实现瀑布流加载图片原理
2016/02/02 Javascript
js实现的下拉框二级联动效果
2016/04/30 Javascript
全面理解JavaScript中的继承(必看)
2016/06/16 Javascript
nodejs进阶(6)—连接MySQL数据库示例
2017/01/07 NodeJs
javascript作用域链与执行环境详解
2017/03/25 Javascript
说说Vue.js中的functional函数化组件的使用
2019/02/12 Javascript
自己使用总结Python程序代码片段
2015/06/02 Python
Python的Django框架中的URL配置与松耦合
2015/07/15 Python
基于Python函数的作用域规则和闭包(详解)
2017/11/29 Python
linecache模块加载和缓存文件内容详解
2018/01/11 Python
详解python实现识别手写MNIST数字集的程序
2018/08/03 Python
Python基于pygame实现单机版五子棋对战
2019/12/26 Python
给keras层命名,并提取中间层输出值,保存到文档的实例
2020/05/23 Python
Python爬虫之Selenium实现窗口截图
2020/12/04 Python
90后毕业生的求职信范文
2013/09/21 职场文书
给学校的建议书
2014/03/12 职场文书
日语专业求职信
2014/07/04 职场文书
安全生产知识竞赛活动总结
2014/07/07 职场文书
校园主题婚礼活动策划方案
2014/09/15 职场文书
领导班子对照检查剖析材料
2014/10/13 职场文书
2015年机关党建工作总结
2015/05/22 职场文书
2016高中社会实践心得体会范文
2016/01/14 职场文书
微信小程序实现聊天室功能
2021/06/14 Javascript
vue elementUI批量上传文件
2022/04/26 Vue.js
Python按顺序遍历并读取文件夹中文件
2022/04/29 Python