分享

Python selenium实现大麦网自动购票过程解析

 求知881 2023-07-26 发布于河南
  更新时间:2022年05月10日 10:20:34   作者:松鼠爱吃饼干  
大麦网是中国综合类现场娱乐票务营销平台,业务覆盖演唱会、 话剧、音乐剧、体育赛事等领域,今天我们要用代码来实现他的购票过程,感兴趣的朋友一起看看吧
+
目录

先来看看完成后的效果是怎么样的

开发环境

  • 版 本:anaconda(python3.8.8)

  • 编辑器:pycharm

代码实现步骤

  • 实现免登陆

  • 选座并且下单

实现免登陆

1
2
3
4
5
damai_url = 'https://www./'
# 登录
login_url = 'https://passport./login?ru=https%3A%2F%2Fwww.%2F'
# 抢票目标页
target_url = 'https://detail./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'

初始化加载

1
2
3
4
5
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'# 当前浏览器驱动对象

登录

1
2
3
4
5
6
7
8
9
10
11
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: 登录网站时出现的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)

假如说我现在本地有 cookies.pkl 那么 直接获取

1
2
3
4
5
6
7
8
9
10
def get_cookie(self):
    cookies = pickle.load(open('cookies.pkl', 'rb'))
    for cookie in cookies:
        cookie_dict = {
            'domain': '.'# 必须要有的, 否则就是假登录
            'name': cookie.get('name'),
            'value': cookie.get('value')
        }
        self.driver.add_cookie(cookie_dict)
    print('###载入cookie###')

运行代码可以得到所需要的cookis,这样就可以实现免登录

打开浏览器

1
2
3
4
5
6
7
8
9
10
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()

实现购票

选票操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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

选择座位

1
2
3
4
5
6
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()

下单操作

1
2
3
4
5
6
7
8
9
10
11
12
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()

判断元素是否存在

1
2
3
4
5
6
7
8
9
def isElementExist(self, element):
    flag = True
    browser = self.driver
    try:
        browser.find_element_by_xpath(element)
        return flag
    except:
        flag = False
        return flag

购票完成, 退出

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

到此这篇关于Python selenium 简单的实现大麦网自动购票过程的文章就介绍到这了,更多相关Python大麦网自动购票内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约