用作记录
from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
from selenium.webdriver import ChromeOptions
import pickle,time,os,sys
import requests,re,json
from urllib.parse import quote
class exclusiveSpider(object):
def __init__(self,username,password):
self.url= ''
self.username=username
self.password=password
self.pathFile = "cookies.pkl" #cookies 第一个号
self.driver=self.newOption()
self.driver.get(self.url)
# self.driver.implicitly_wait(20) # 隐性等待,最长等30秒,全局的
# self.is_login()
# self.headers= {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'}
# self.session=requests.session()
# self.session.cookies=requests.utils.cookiejar_from_dict(self.get_requests_cookies())
def newOption(self):
try:
executable_path=os.path.split(os.path.realpath(sys.argv[0]))[0]+'//Mac_ChromeDriver//chromedriver'
option = webdriver.ChromeOptions() #实例化一个ChromeOptions对象
option.add_experimental_option('excludeSwitches', ['enable-automation']) #以键值对的形式加入参数,防止检测
option.add_argument('disable-infobars') #去除自动化控制提示
option.add_argument('lang=zh_CN.UTF-8') #设置中文
# prefs = {"profile.managed_default_content_settings.images": 2,'permissions.default.stylesheet':2}
# option.add_experimental_option("prefs", prefs)
driver=webdriver.Chrome(executable_path=executable_path,options=option)
except TimeoutException as e:
print(e)
return driver
def is_login(self):
'''判断当前是否登陆'''
self.driver.refresh() #刷新页面
html = self.driver.page_source
if html.find("请登入") == -1: #利用用户名判断是否登陆
# 没登录 ,则手动登录
self.login()
else:
#已经登录 尝试访问搜索记录,可以正常访问
self.driver.refresh()
time.sleep(5) # 延时看效果
print('登入成功')
def login(self):
'''手动登陆'''
for i in range(31,1,-1):
time.sleep(1)
print("请在-{}-秒内完成登入".format(i))
self.driver.refresh()
def set_cookie(self):
'''往浏览器添加cookie'''
'''利用pickle序列化后的cookie'''
try:
self.driver.delete_all_cookies()
cookies = pickle.load(open(self.pathFile, "rb"))
for cookie in cookies:
cookie_dict = {
'name': cookie.get('name'),
'value': cookie.get('value'),
}
self.driver.add_cookie(cookie_dict)
except Exception as e:
print('cookies文件不存在')
print(e)
def get_content(self):
path=os.path.split( os.path.realpath( sys.argv[0]))[0]+'\\Mac_ChromeDriver\\tieba_content.txt'
with open(path,'r') as f:
data = f.read()
return data
def get_requests_cookies(self):
if not os.path.exists(self.pathFile):
self.session.headers.clear()
print('Cookies.pkl 文件不存在')
exit()
else:
cookies1 ={} #下面是第一种方法 ,硬塞到get(cookies=cookies1),第二种就是加到session
# cookies = pickle.load(open(self.pathFile, "rb"))
# for cookie in cookies:
# cookies1[cookie['name']]=cookie['value']
# return cookies1
cookies = pickle.load(open(self.pathFile, "rb"))
for cookie in cookies:
cookies1[cookie['name']]=cookie['value']
return cookies1
def run(self):
#写功能
print('请登入账号密码确保在抢购页面')
raw =input("请输入数字0:开始抢购")
print('冲啊!!!')
if raw =="0":
while True:
try:
if self.driver.find_element_by_link_text('加入购物车'):
self.driver.find_element_by_link_text('加入购物车').click()
break
except:
print("找不到加入购物车按钮")
while True:
try:
if self.driver.find_element_by_class_name('btn-addtocart'):
self.driver.find_element_by_class_name('btn-addtocart').click()
break
except:
print("找不到去结算按钮")
while True:
try:
if self.driver.find_element_by_link_text('去结算'):
self.driver.find_element_by_link_text('去结算').click()
break
except:
print("找不到结算按钮")
while True:
try:
if self.driver.find_element_by_id('order-submit'):
self.driver.find_element_by_id('order-submit').click()
break
except:
print("找不到提交订单按钮")
# while True:
# try:
# if self.driver.find_element_by_xpath('//*[@id="payChannelListId"]/div[6]/div/div[3]/span'):
# self.driver.find_element_by_xpath('//*[@id="payChannelListId"]/div[6]/div/div[3]/span').send_keys('123456')
# break
# except:
# print("找不到mima按钮")
print('成功抢到商品')
print('结束')
else:
print('不抢')
if __name__ == '__main__':
username = "" #账号
password = " " #密码
ex = exclusiveSpider(username,password)
ex.run()