说明:本篇博客基于selenium 4.1.0
说明
cookie复用,跳过登录步骤
代码语言:txt复制# 1. 首次运行,手动登录进网站
# 2. 记录cookie信息到本地
cookie = driver.get_cookies()
# 3. 后续再次登录时,传入本地cookie信息,登录进网站
for i in cookie:
driver.add_cookie(i)
代码示例
代码语言:txt复制import os
import yaml
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('https://work.weixin.qq.com/wework_admin/loginpage_wx')
if not os.path.exists("resource"):
os.mkdir("resource")
# 判断cookie是否存在,有则使用cookie跳过登录,无则手动登录
if os.path.exists("resource/cookie.yaml"):
# 读取cookie,传入浏览器中
cookie = yaml.safe_load(open("resource/cookie.yaml"))
for i in cookie:
driver.add_cookie(i)
# 进入网站
driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
else:
# 扫码登录,等待页面加载
WebDriverWait(driver, 60).until(expected_conditions.url_contains("wework_admin/frame"))
# 存入cookie信息到本地
cookie = driver.get_cookies()
with open("resource/cookie.yaml", "w") as f:
yaml.safe_dump(cookie, f)
time.sleep(3)
driver.quit()