無效的 Cookie 域名

**無效的 Cookie 域名**錯誤是WebDriver 錯誤,當嘗試在與當前文件不同的域名下設定Cookie時發生。

在 WebDriver 中,不允許為除當前瀏覽上下文文件域名之外的其他域名設定 Cookie。

如果文件是“排斥 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

另請參閱