org.openqa.selenium.InvalidCookieDomainException:文档使用 Selenium 和 WebDriver 是 cookie-averse

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse using Selenium and WebDriver

我正在尝试将 cookie 推送到从上一个会话存储的 selenium firefox webdriver,但出现错误:

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse

我读了这篇文章HTML Standard Cookie-averse,但什么都不懂。

那么,问题是如何将 cookie 推送到从前一个存储的 webdriver 会话中?

这个错误信息...

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse

...暗示有人非法尝试在与当前文档不同的域下设置 cookie。


详情

根据 HTML-Living Standard Specification,在以下情况下,Document Object 可能被归类为 cookie-averse Document 对象:

  • 没有 Browsing Context.
  • 的文档
  • URL 方案不是网络方案的文档。

深入探讨

根据 Invalid cookie domain,当您访问 cookie-averse 文档(例如本地磁盘上的文件)时,可能会发生此错误。

举个例子:

  • 示例代码:

      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
    

解决方案

如果您存储了来自域 example.com 的 cookie,这些存储的 cookie 不能 通过 webdriver 会话推送到任何其他不同的域,例如example.edu。存储的 cookie 只能在 example.com 内使用。此外,为了将来自动登录用户,您只需要存储 cookie 一次,即用户登录时。在添加回 cookie 之前,您需要浏览到收集 cookie 的同一域。


例子

例如,您可以在用户登录应用程序后存储 cookie,如下所示:

from selenium import webdriver
import pickle

driver = webdriver.Chrome()
driver.get('http://demo.guru99.com/test/cookie/selenium_aut.php')
driver.find_element_by_name("username").send_keys("abc123")
driver.find_element_by_name("password").send_keys("123xyz")
driver.find_element_by_name("submit").click()

# storing the cookies
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
driver.quit()

以后如果你想让用户自动登录,你需要先浏览到特定的域/url然后你必须添加cookie如下:

from selenium import webdriver
import pickle

driver = webdriver.Chrome()
driver.get('http://demo.guru99.com/test/cookie/selenium_aut.php')

# loading the stored cookies
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    # adding the cookies to the session through webdriver instance
    driver.add_cookie(cookie)
driver.get('http://demo.guru99.com/test/cookie/selenium_cookie.php')

参考

您可以在以下位置找到详细讨论:

  • Error when loading cookies into a Python request session

谢谢 DebanjanB! 我试图在驱动程序启动后 打开 URL 选项卡之前推送 cookie。

工作解决方案:

driver.get('http://mydomain')
driver.manage.addCookie(....)
driver.get('http://mydomain')

只需打开一个标签,添加 cookie 并重新打开一个标签

我猜你的情况是你在用 driver.get('http://mydomain') 获得 url 之前用 driver.manage.addCookie(....) 设置了 cookie。

Cookie can be only add to the request with same domain.
When webdriver init, it's request url is `data:` so you cannot add cookie to it.
So first make a request to your url then add cookie, then request you url again.