天天看點

Python制作【大麥網】自動搶票程式

前言

大麥網,是中國綜合類現場娛樂票務營銷平台,業務覆寫演唱會、 話劇、音樂劇、體育賽事等領域。

但是因為票數有限,還有黃牛們不能丢了飯碗,是以導緻了,很多人都搶不到票

那麼,今天帶大家用Python來制作一個自動搶票的腳本小程式

知識點:

  • 面向對象程式設計
  • selenium 操作浏覽器
  • pickle 儲存和讀取Cookie實作免登陸
  • time 做延時操作
  • os 建立檔案,判斷檔案是否存在

開發環境:

  • 版 本:anaconda5.2.0(python3.6.5)
  • 編輯器:pycharm

【付費VIP完整版】隻要看了就能學會的教程,80集Python基礎入門視訊教學

先導入本次所需的子產品

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

最後看下效果如何

對于本篇文章有疑問的同學也可以點這裡