前言

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

但是因为票数有限,还有黄牛们不能丢了饭碗,所以导致了,很多人都抢不到票

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

知识点:

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

开发环境:

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

【付费VIP完整版】只要看了就能学会的教程,80集Python基础入门视频教学​www.bilibili.com/video/BV1544y1C7g4?share_source=copy_web

先导入本次所需的模块

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

~~~python

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

~~~python

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全套学习资料,都是我自己学习时整理的,希望可以帮到你,一起加油!

有需要的小伙伴,可以V扫描下方二维码免费领取

1️⃣零基础入门

① 学习路线

对于从来没有接触过Python的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

② 路线对应学习视频

还有很多适合0基础入门的学习视频,有了这些视频,轻轻松松上手Python~

③练习题

每节视频课后,都有对应的练习题哦,可以检验学习成果哈哈!

2️⃣国内外Python书籍、文档

① 文档和书籍资料

3️⃣Python工具包+项目源码合集

①Python工具包

学习Python常用的开发软件都在这里了!每个都有详细的安装教程,保证你可以安装成功哦!

②Python实战案例

光学理论是没用的,要学会跟着一起敲代码,动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。100+实战案例源码等你来拿!

③Python小游戏源码

如果觉得上面的实战案例有点枯燥,可以试试自己用Python编写小游戏,让你的学习过程中增添一点趣味!

4️⃣Python面试题

我们学会了Python之后,有了技能就可以出去找工作啦!下面这些面试题是都来自阿里、腾讯、字节等一线互联网大厂,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

上述所有资料 ⚡️ ,朋友们如果有需要的,可以扫描下方二维码免费领取 ​

文章链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。