You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Chrome WebDriver刷新页面时如何保留Cookie维持登录状态?

解决Selenium刷新页面后Cookie丢失导致登出的问题

你遇到的问题源于Selenium默认启动的Chrome是干净的临时环境,不会持久化会话Cookie,且部分网站会检测自动化工具并销毁会话。以下是几种可行的解决方法:

方案1:加载本地Chrome用户数据目录

直接复用你日常使用的Chrome配置(包含已保存的登录Cookie),让自动化环境的会话状态和正常Chrome保持一致,刷新后不会丢失登录状态。

修改代码中的Options配置:

options = Options()
# 替换成你自己的Chrome用户数据路径
# Windows示例路径
options.add_argument(r"user-data-dir=C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data")
# Linux示例路径:options.add_argument(r"user-data-dir=/home/你的用户名/.config/google-chrome/")
# Mac示例路径:options.add_argument(r"user-data-dir=/Users/你的用户名/Library/Application Support/Google/Chrome/")

# 额外添加隐藏自动化检测的选项,避免网站拦截会话
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

注意:启动前必须关闭所有正在运行的Chrome窗口,否则会出现端口占用错误。

方案2:手动保存并恢复Cookie

登录成功后主动保存当前会话的Cookie,刷新页面后重新注入Cookie,恢复登录状态。

修改后的完整代码片段:

from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pause
from datetime import datetime
from selenium.webdriver.chrome.options import Options


options = Options()
# 添加隐藏自动化检测的选项
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(options=options)
driver.get("Website")
time.sleep(2)

# 执行登录流程
LogIn = driver.find_element(By.ID, "log-in-link")
LogIn.click()
email = driver.find_element(By.ID, "email")
email.send_keys("email")
password = driver.find_element(By.ID, "sign-in-password")
password.send_keys("password")
SignIn = driver.find_element(By.CLASS_NAME, "sign-in-btn")
SignIn.click()

# 等待登录会话稳定(建议替换为显式等待,比如等待用户头像出现)
time.sleep(3)
# 保存当前会话的所有Cookie
cookies = driver.get_cookies()

# 等待预订时间
pause.until(datetime(2025, 2, 12, 8, 0, 0))

# 重新打开目标页面
driver.get("Website")

# 恢复Cookie
for cookie in cookies:
    # 转换expiry值为整数(部分Cookie的expiry是浮点数,Selenium要求为int)
    if "expiry" in cookie:
        cookie["expiry"] = int(cookie["expiry"])
    driver.add_cookie(cookie)

# 刷新页面使Cookie生效
driver.refresh()

# 此时页面应保持登录状态

方案3:优化等待逻辑,减少页面重载

如果只是需要等待预订开放,不一定需要完全刷新页面:

  • 使用driver.execute_script("location.reload(true);")强制刷新(跳过缓存)
  • 或者定期检查页面预订按钮的状态,而不是直接刷新整个页面,降低会话丢失的风险

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:54:51