为了顺利买到演唱会的票用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 相关文章推荐
Python实现简单截取中文字符串的方法
Jun 15 Python
Python实现字典的key和values的交换
Aug 04 Python
python 如何快速找出两个电子表中数据的差异
May 26 Python
Python实现的弹球小游戏示例
Aug 01 Python
Python中的浮点数原理与运算分析
Oct 12 Python
python 异或加密字符串的实例
Oct 14 Python
Python标准库使用OrderedDict类的实例讲解
Feb 14 Python
python简单鼠标自动点击某区域的实例
Jun 25 Python
Python封装成可带参数的EXE安装包实例
Aug 24 Python
python数据处理之如何选取csv文件中某几行的数据
Sep 02 Python
python自动化测试之异常及日志操作实例分析
Nov 09 Python
自定义Django默认的sitemap站点地图样式
Mar 04 Python
Python 游戏大作炫酷机甲闯关游戏爆肝数千行代码实现案例进阶
Python实现老照片修复之上色小技巧
Python anaconda安装库命令详解
Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析
Python爬虫入门案例之爬取二手房源数据
Python爬虫入门案例之回车桌面壁纸网美女图片采集
Python Django模型详解
You might like
php google或baidu分页代码
2009/11/26 PHP
启用OPCache提高PHP程序性能的方法
2019/03/21 PHP
一直复略了的一个问题,关于表单重复提交
2007/02/15 Javascript
学习ExtJS Panel常用方法
2009/10/07 Javascript
Function.prototype.call.apply结合用法分析示例
2013/07/03 Javascript
node.js中的console.assert方法使用说明
2014/12/10 Javascript
node.js操作mongodb学习小结
2015/04/25 Javascript
Javascript中神奇的this
2016/01/20 Javascript
JS代码随机生成姓名、手机号、身份证号、银行卡号
2016/04/27 Javascript
详解vue2路由vue-router配置(懒加载)
2017/04/08 Javascript
JavaScript获取某一天所在的星期
2019/09/05 Javascript
python特性语法之遍历、公共方法、引用
2018/08/08 Python
Python找出微信上删除你好友的人脚本写法
2018/11/01 Python
python 多线程将大文件分开下载后在合并的实例
2018/11/09 Python
pandas去除重复列的实现方法
2019/01/29 Python
python 实现提取某个索引中某个时间段的数据方法
2019/02/01 Python
详解Python匿名函数(lambda函数)
2019/04/19 Python
matlab灰度图像调整及imadjust函数的用法详解
2020/02/27 Python
python读取mysql数据绘制条形图
2020/03/25 Python
pycharm 多行批量缩进和反向缩进快捷键介绍
2021/01/15 Python
Python使用pyenv实现多环境管理
2021/02/05 Python
python推导式的使用方法实例
2021/02/28 Python
美国用餐电影院:Alamo Drafthouse Cinema
2020/01/23 全球购物
main 主函数执行完毕后,是否可能会再执行一段代码,给出说明
2012/12/05 面试题
Oracle中delete,truncate和drop的区别
2016/05/05 面试题
Servlet方面面试题
2016/09/28 面试题
opencv实现图像几何变换
2021/03/24 Python
营销与策划专业毕业生求职信
2013/11/01 职场文书
班风学风建设方案
2014/05/06 职场文书
工程项目经理任命书
2014/06/05 职场文书
计算机求职信
2014/07/02 职场文书
团员年度个人总结
2015/02/26 职场文书
PHP实现rar解压读取扩展包小结
2021/06/03 PHP
python 判断文件或文件夹是否存在
2022/03/18 Python
《地。-关于地球的运动-》单行本第七集上市,小说家朝井辽献上期待又害怕的推荐文
2022/03/31 日漫
优化Mysql查询的示例
2022/04/26 MySQL