当前位置: 首页 > news >正文

演唱会总是抢不到票?教你用Python制作一个自动抢票脚本

人生苦短 我用python

这个大家应该都知道吧?

是中国综合类现场娱乐票务营销平台,
业务覆盖演唱会、 话剧、音乐剧、体育赛事等领域。

如何快速抢票?

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

本文源码+python安装包 : 点击此处跳转文末名片获取

在这里插入图片描述

知识点:

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

开发环境:

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

第三方库:

selenium >>> pip install selenium==3.4.1

步骤

1. 实现免登陆
第一次登陆的时候 会帮助我记录我们的登陆信息 set_cookie 登陆成功之后 cookie会发生变化 后续抢票: 直接使用我们记录好的登陆信息 get_cookie

2. 抢票并且下单

准备好了之后就开始正式写代码吧!

在这里插入图片描述

首先导入本次所需的模块

from selenium import webdriver  # 操作谷歌浏览器 需要额外安装的 并且现在安装这个模块得指定版本 3.4
from time import sleep
import pickle  # 保存和读取cookie实现免登录的工具
import os   # 操作文件的模块

第一步,实现免登录

确定目标,设置全局变量

damai_url = ""
# 登录页
login_url = ""
# 抢票目标页
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 != '网站名称':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"))  # 载入cookiefor 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 = Truebrowser = self.drivertry:browser.find_element_by_xpath(element)return flagexcept:flag = Falsereturn 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').textif buybutton == "提交缺货登记":# 改变现有状态self.status=2self.driver.get(target_url)print('###抢票未开始,刷新等待开始###')continueelif buybutton == "立即预定":self.driver.find_element_by_class_name('buybtn').click()# 改变现有状态self.status = 3elif 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 = 5except:print('###未跳转到订单结算界面###')title = self.driver.titleif 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]/divwhile 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()

效果大致演示

在这里插入图片描述

最后祝大家都能抢到心仪的票票~

👇问题解答 · 源码获取 · 技术交流 · 抱团学习请联系👇

http://www.lryc.cn/news/38981.html

相关文章:

  • 【系统开发】WebSocket + SpringBoot + Vue 搭建简易网页聊天室
  • Learning C++ No.14【STL No.4】
  • 高速PCB设计指南(八)
  • 什么是腾讯云关系型数据库(MySQL/SQL Server/MariaDB/PostgreSQL详解)
  • 进程通信相关概念
  • 05.Java的运算符
  • 轮转数组(力扣189)
  • 主流的“对象转换工具”使用示例大全以及性能的对比
  • 分享10个不错的C语言开源项目
  • 【阅读笔记】JavaScript设计模式与开发实践2--闭包与单例、策略模式
  • 设计模式(二十)----行为型模式之责任链模式
  • 数据持久化层--冷热分离
  • Ubuntu16.04系统 VSCode中python开发插件的安装
  • buuctf-pwn write-ups (12)
  • Linux- 系统随你玩之--网络上的黑客帝国
  • Python每日一练(20230312)
  • 人生又有几个四年
  • 第九章:Java集合
  • 嵌入式学习笔记——STM32的USART通信概述
  • MySQL性能优化
  • C语言/动态通讯录
  • 我用Compose做了一个地图轮子OmniMap
  • STM32之SPI
  • 02 深度学习环境搭建
  • PHP导入大量CSV数据的方法分享
  • 代码看不懂?ChatGPT 帮你解释,详细到爆!
  • 【MyBatis】篇三.自定义映射resultMap和动态SQL
  • 什么是API?(详细解说)
  • 比cat更好用的命令!
  • MySQL、HBase、ElasticSearch三者对比