selenium 练习带cookie免验证登录 (小试文库)
from selenium import webdriverimport time
import json
def browser_initial():
""""
进行浏览器初始化
"""
browser= webdriver.Chrome(executable_path=r'C:\Program Files\Google\Chrome\Application\chromedriver.exe') # 调用Chrome 驱动,生成浏览器对象
log_url = 'https://www.baidu.com'
return log_url, browser
def get_cookies(log_url, browser):
"""
获取cookies保存至本地
"""
browser.get(log_url)
time.sleep(25)# 进行扫码
dictCookies = browser.get_cookies()# 获取list的cookies
print(dictCookies)
jsonCookies = json.dumps(dictCookies)# 转换成字符串保存
with open('damai_cookies.txt', 'w') as f:
f.write(jsonCookies)
print('cookies保存成功!')
if __name__ == "__main__":
tur = browser_initial()
get_cookies(tur, tur)
#-------------------------------------------------------------------------------------
fromselenium import webdriver
fromselenium.webdriver.common.by import By
fromselenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC
import time ,json,os
url = 'https://wenku.baidu.com/view/31b87809ab8271fe910ef12d2af90242a995ab45.html'
def log_cokie(browser):
"""
从本地读取cookies并刷新页面,成为已登录状态
"""
os.chdir('F:\\pythonwork')
with open('damai_cookies.txt', 'r', encoding='utf8') as f:
listCookies = json.loads(f.read())
print(listCookies)
browser.get('https://www.baidu.com')
for cookie in listCookies:
print(cookie)
browser.add_cookie(cookie)
browser.refresh()# 刷新网页,cookies才成功
log_cokie(browser)
try:
browser.get(url)
print(browser.get_cookies())
Cl = browser.find_element(By.CSS_SELECTOR,".fold-page-text")
browser.execute_script('arguments.click();',Cl) #被检测到了不准点击点击后把元素停换成了别的元素
time.sleep(5)#被遮挡了
foriin range(1,4):
browser.execute_script(f'window.scrollTo(0,document.body.scrollHeight*{i/3})')
time.sleep(3)
Cls = browser.find_elements(By.CLASS_NAME,"dialog-container")
forcl2inCls:
try:
Cl2 = cl2.find_element_by_tag_name('i')
browser.execute_script('arguments.click();',Cl2) #被检测到了不准点击点击后把元素停换成了别的元素
time.sleep(3)
except:
continue
time.sleep(5)
pays = browser.find_elements(By.CLASS_NAME,'ie-fix')
print(len(pays))
for payinpays:
print(pay.text)
with open('python_items.txt','a')asf:
f.write(pay.text)
time.sleep(60)
print("over")
finally:
browser.close()
页:
[1]