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

Python+Chromedriver登录后域名变更时如何加载Cookie?

解决方案

错误原因

Selenium 的 add_cookie() 方法要求当前浏览器访问的域名必须与 Cookie 的 domain 属性匹配(符合 Cookie 域名规则)。你遇到的 InvalidCookieDomainException 就是因为当前页面域名和要添加的 Cookie 域名不匹配导致的。

解决步骤

  1. 按域名分组处理 Cookie
    把 Cookie 按 domain 分成根域名(.example.net)和子域名(member.example.net)两组,分别在对应域名下添加。

  2. 先访问对应域名再添加 Cookie
    Selenium 不允许给未访问过的域名添加 Cookie,所以添加某域名的 Cookie 前,必须先访问该域名下的任意页面(哪怕是站点首页或空白页)。

修正后的代码示例

from selenium import webdriver
import sys

# 你的Cookie列表
cookies = [
    {'domain': '.example.net', 'expiry': 111, 'httpOnly': True, 'name': 'reme', 'path': '/', 'secure': True, 'value': '1111'},
    {'domain': 'member.example.net', 'httpOnly': True, 'name': 'reme22', 'path': '/', 'secure': True, 'value': '2222'}
]

browser = webdriver.Chrome()

# 处理根域名Cookie:先访问根域名页面
browser.get("https://example.net")
for cookie in [c for c in cookies if c['domain'] == '.example.net']:
    try:
        browser.add_cookie(cookie)
    except Exception as e:
        print(type(e), e, sys.exc_info()[-1].tb_lineno)

# 处理子域名Cookie:先访问子域名页面
browser.get("https://member.example.net")
for cookie in [c for c in cookies if c['domain'] == 'member.example.net']:
    try:
        browser.add_cookie(cookie)
    except Exception as e:
        print(type(e), e, sys.exc_info()[-1].tb_lineno)

# 刷新页面验证登录状态
browser.refresh()
print(browser.get_cookies())

额外注意事项

  • 如果 Cookie 的 domain 是 member.example.net,必须确保当前访问的页面域名完全一致(不能是 www.member.example.net 或其他衍生子域名)。
  • 若 Cookie 标记了 secure: True,必须通过 HTTPS 协议访问页面,否则无法成功添加。
  • 无需逐个添加 Cookie 后刷新页面,全部添加完成后再刷新即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:24:06