[Damai.com automatically grabs tickets] 100% instant sale. If the ticket issuance fails, I will quit the programming circle!

Preface

Damai.com is a comprehensive live entertainment ticketing marketing platform in China. Its business covers concerts, dramas, musicals, sports events and other fields. Today, we are going to use code to realize his ticket purchase process.

Let’s first take a look at the finished effect.

Insert image description here

development environment

  • Edition book: anaconda (python3.8.8)
  • Editor: pycharm

Code implementation steps

  • Achieve no need to log in
  • Select your seat and place your order

Achieve no need to log in

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.6ee64d156yMCV9&id=672706937093&clicktitle=%E7%95%99%E5%A3%B0%E7%8E%A9%E5%85%B72022%E3%80%8C%E6%97%B6%E9%97%B4%E7%9A%84%E8%B7%A8%E5%BA%A6%E3%80%8D%E5%B7%A1%E6%BC%94Vol%C2%B71%20%E9%95%BF%E6%B2%99%E7%AB%99'

Initial load

from selenium import webdriver  # 操作浏览器的工具

def __init__(self):
    self.status = 0   # 状态, 表示当前操作执行到了哪个步骤
    self.login_method = 1  # {0:模拟登录, 1:cookie登录}自行选择登录的方式
    self.driver = webdriver.Chrome(executable_path='chromedriver.exe')  # 当前浏览器驱动对象

Log in

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_cookies()             # 没有文件的情况下, 登录一下
        else:
            self.driver.get(target_url)  # 跳转到抢票页
            self.get_cookie()           # 并且登录

cookies: Appears when logging into the website

import time       

def set_cookies(self):
    self.driver.get(damai_url)
    print('###请点击登录###')
    # 我没有点击登录,就会一直延时在首页, 不会进行跳转
    while self.driver.title.find('大麦网-全球演出赛事官方购票平台') != -1:
        sleep(1)
    print('###请扫码登录###')
    # 没有登录成功
    while self.driver.title != '大麦网-全球演出赛事官方购票平台-100%正品、先付先抢、在线选座!':
        sleep(1)
    print('###扫码成功###')
    # get_cookies: driver里面的方法
    pickle.dump(self.driver.get_cookies(), open('cookies.pkl', 'wb'))
    print('###cookie保存成功###')
    self.driver.get(target_url)

Suppose I have cookies locally.[pkl]

def get_cookie(self):
    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###')

Running the code can get the required cookies, so that no login is required.

Insert image description here

Open browser

def enter_concert(self):
    print('###打开浏览器,进入大麦网###')
    # 调用登录
    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()

Realize ticket purchase

Ballot operations

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)  # 刷新页面 继续执行操作
                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('正在加载.......')
                    # 如果当前购票人信息存在 就点击
                    if self.isElementExist('//*[@id="container"]/div/div[9]/button'):
                        # 下单操作
                        self.check_order()
                        break

Select your seat

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()

Order operation

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('//*[@id="container"]/div/div[9]/button').click()

Determine whether the element exists

def isElementExist(self, element):
    flag = True
    browser = self.driver
    try:
        browser.find_element_by_xpath(element)
        return flag
    except:
        flag = False
        return flag

Ticket purchase completed, exit

def finish(self):
    self.driver.quit()

Guess you like

Origin blog.csdn.net/XM67_/article/details/131562382