自动登陆获取cookies:
import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium.webdriver.chrome.options import Options
ser = Service()
ser.path = r'.\chromedriver.exe'
# 去掉自动化软件控制的检测
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled") # 去掉自动化控制
bro = webdriver.Chrome(service=ser, options=options)
bro.get('https://www.cnblogs.com/')
# 隐士等待
bro.implicitly_wait(10)
# 窗口全屏
bro.maximize_window()
# 寻找页面登陆按钮并点击
login_btn = bro.find_element(By.LINK_TEXT, '登录')
login_btn.click()
time.sleep(2)
# 找到用户名和密码输入框
username = bro.find_element(By.CSS_SELECTOR, '#mat-input-0')
password = bro.find_element(By.ID, 'mat-input-1')
# 找到登陆提交按钮
submit_btn = bro.find_element(By.CSS_SELECTOR,
'body > app-root > app-sign-in-layout > div > div > app-sign-in > app-content-container > div > div > div > form > div > button')
# 找到验证按钮
code = bro.find_element(By.ID, 'rectMask')
time.sleep(1)
username.send_keys('账号名')
time.sleep(1)
password.send_keys('密码')
time.sleep(1)
submit_btn.click() # 一种情况直接登录成功 一种情况会弹出验证码
# 点击验证按钮
code.click()
# 到现在,是登录成功的状态
# 取出cookie存起来
cookies = bro.get_cookies()
with open('cnblogs.json', 'w', encoding='utf-8') as f:
json.dump(cookies, f)
bro.close()
使用获取的cookies自动登陆
import json
import time
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.chrome.options import Options
ser = Service()
ser.path = r'.\chromedriver.exe'
# #### 绕过浏览器检测到 自动化软件控制
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled") # 去掉自动化控制
bro = webdriver.Chrome(service=ser, options=options)
bro.get("https://www.cnblogs.com")
bro.implicitly_wait(10)
bro.maximize_window()
# 读出cookie---》写入到浏览器中
with open('cnblogs.json', 'rt', encoding='utf-8') as f:
cookies = json.load(f)
for cookie in cookies:
bro.add_cookie(cookie)
time.sleep(2)
bro.refresh()
time.sleep(5)
bro.close()