无效的 cookie 域

无效的 cookie 域(invalid cookie domain)错误是一种 WebDriver 错误,发生在尝试将 cookie 设置到与当前文档不同 下时。

在 WebDriver 中,不允许为当前 浏览上下文 文档 域以外的其他域设置 cookie。

如果文档是“cookie-averse”(对 cookie 敏感)的,即文档不是通过 http://https://ftp:// 加载的,也会发生此错误。

示例

其他域

如果当前域是 example.com,则无法为域 example.org 添加 cookie

python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
session.get("https://example.com/")
try:
    cookie = {"name": "foo",
              "value": "bar",
              "domain": "example.org"}
    session.add_cookie(cookie)
except exceptions.InvalidCookieDomainException as e:
    print(e.message)

输出

InvalidCookieDomainException: https://example.org/

当您访问对 cookie 敏感的文档(例如本地磁盘上的文件)时,也可能会发生此错误

python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
session.get("file:///home/jdoe/document.html")
try:
    foo_cookie = {"name": "foo", "value": "bar"}
    session.add_cookie(foo_cookie)
except exceptions.InvalidCookieDomainException as e:
    print(e.message)

输出

InvalidCookieDomainException: Document is cookie-averse

另见