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