import os import time import pickle # 实现读取cookie 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?id=779820312992' class Concert: # 初始化加载 def __init__(self): self.status = 0 # 状态,表示当前操作执行到那一步了 self.login_method = 1 # {0: 模拟登录, 1:cookie登录} self.driver = webdriver.Edge() # 初始化浏览器 # cookies: 登录网站的时候出现的,记录用户信息 def set_cookies(self): self.driver.get(login_url) # 帮助我们打开一个网页 print("###请扫码登录###") time.sleep(20) print("###登录成功###") # cookie.pkl pickle.dump(self.driver.get_cookies(), open('cookies.pkl', 'wb')) print("###cookie保存成功###") # 抢票 self.driver.get(target_url) # 如果当前我已经有了cookie.pkl def get_cookies(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成功###") # 登录 def login(self): # 如果为0 模拟登陆一下 if self.login_method == 0: self.driver.get(login_url) elif self.login_method == 1: # 如果当前目录下 没有这个cookie.pkl这个文件 if not os.path.exists('cookies.pkl'): # 登录一下 登录信息记录 self.set_cookies() else: self.driver.get(target_url) # 登录一下 通过selenium传入一些用户信息 self.get_cookies() # 打开浏览器 def enter_concert(self): print("###打开浏览器,进入大麦网###") # 调用login self.login() self.driver.refresh() self.status = 2 print("###登录成功###") # 二、抢票且下单 # 选票操作 def choose_ticket(self): if self.status == 2: print('=' * 30) print('###请开始日期选择以及票价选择###') print(self.driver.title.find("确认订单") == 1) while self.driver.title.find("确认订单") == -1: # 下单按钮 buybutton = self.driver.find_element_by_class_name("buybtn").text if buybutton == '提交缺货登记': self.driver.refresh() elif buybutton == '立即购买': self.driver.find_element_by_class_name("buybtn").click() self.status = 5 elif buybutton == '选座购买': self.driver.find_element_by_class_name("buybtn").click() self.status = 4 else: self.status = 100 title = self.driver.title if title == '选座购买': # 执行选座操作 self.status = 10 elif title == '确认订单': # 实现下单的逻辑 while True: print('###正在加载###') self.check_order() break # 下单操作 def check_order(self): if self.status in [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() if '__main__' == __name__: con = Concert() con.enter_concert() time.sleep(1) con.choose_ticket()