编写python抢票程序
from selenium import webdriver # 操作谷歌浏览器 需要额外安装的 并且现在安装这个模块得指定版本 3.4
from time import sleep
import pickle # 保存和读取cookie实现免登录的工具
import os # 操作文件的模块
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
damai_url = 'https://www.damai.cn/'
login_url = 'https://passport.damai.cn/login?ru=https%3A%2F%2Fwww.damai.cn%2F%27
target_url = 'https://detail.damai.cn/item.htm?spm=a2oeg.home.card_0.ditem_2.591b23e1XXCcRs&id=674972098463%27
options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled")
class Concert:
# 完成一个初始化
def init(self):
self.status = 0 # 状态码, 表示当前操作执行到了哪个步骤
self.login_method = 1 # {0: 模拟登陆, 1: 免登录}
s=Service(r'C:\Program Files\Google\Chrome\Application\chromedriver.exe')
self.driver = webdriver.Chrome(service=s,options=options)
# cookies: 登录网站时出现的 记录用户信息用的
def set_cookie(self):
"""登陆网站的时候要用的方法 没有登陆的情况下"""
self.driver.get(damai_url) # 打开大麦网主页
print("###请点击登陆###")
# 如果说我一直没有点击登陆? 我是不是这个程序就停在这里了
while self.driver.title.find('大麦网-全球演出赛事官方购票平台') != -1:
sleep(1) # 程序休眠
while self.driver.title != '大麦网-全球演出赛事官方购票平台-100%正品、先付先抢、在线选座!':
sleep(1)
print("###扫码成功###")
pickle.dump(self.driver.get_cookies(), open('cookies.pkl', 'wb')) # 保存cookie
print('###cookie保存成功###')
self.driver.get(target_url)
# 获取已经登陆的cookie
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###')
# 登陆
def login(self):
"""登陆"""
if self.login_method == 0:
self.driver.get(login_url) # 跳转到登陆界面登陆一下
print('###开始登陆###')
elif self.login_method == 1:
# 如果我本地没有cookies.pkl文件
if not os.path.exists('cookies.pkl'):
self.set_cookie() # 没有文件的情况下, 再次登陆一下
else:
self.driver.get(target_url) # 跳转到抢票页面
self.get_cookie() # 登陆信息载入浏览器
# 调用登陆
# 定义一个函数 enter_concert 调用登陆 并且刷新页面 改变登陆成功的标识 status
def enter_concert(self):
"""打开浏览器"""
print('###打开浏览器, 进入大麦网###')
# 调用登陆
self.login()
self.driver.refresh()
self.status = 2
print('###登陆成功###')
def choose_ticket(self):
"""实现选票"""
if self.status == 2:
print("========================")
print("###开始进行日期以及票价选择###")
while self.driver.title.find("确认订单") == -1:
# 如果说我现在能够通过代码定位到这个标
buybutton = self.driver.find_element('class name','buybtn').text
if buybutton == "提交缺货登记":
# 疯狂的刷新页面一直到这个按钮变成其他的内容
self.driver.refresh()
print('###抢票未开始, 刷新等待开始###')
# 退出当前本次循环
continue
elif buybutton == "立即预定":
# 点击下单
self.driver.find_element('class name','buybtn').click()
self.status = 3
elif buybutton == "选座购买":
# 点击下单
self.driver.find_element('class name','buybtn').click()
self.status = 4
elif buybutton == "立即购买":
# 点击下单
self.driver.find_element('class name','buybtn').click()
self.status = 5
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
def choice_seats(self):
# 实现一个选座购买的逻辑
"""选择座位"""
print('请快速选择你的座位!!!')
sleep(3)
# 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/div'):
# # 找到之后疯狂点击确认选座
# self.driver.find_element_by_xpath('//*[@id="app"]/div[2]/div[2]/div[2]/button').click()
def check_order(self):
"""如果状态为 3 4 5 的时候才下单"""
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/span[1]/input').click()
except Exception as e:
print('###购票人信息选中失败, 自行查看元素位置###')
print(e)
# 最后一步提交订单
sleep(0.5) # 太快了不好 导致按钮点击无效
self.driver.find_element_by_xpath('//*[@id="container"]/div/div[9]/button').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 finish(self):
"""抢票成功, 退出当前程序"""
return 0
if name == 'main':
con = Concert()
con.enter_concert()
con.choose_ticket()
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".buybtn"}
解决报错问题
把报错发给我看看