org.openqa.selenium.InvalidCookieDomainException:文档使用 Seleni



我正在尝试将cookie推送到从上一个会话存储的硒火狐网络驱动程序,但是我收到错误:

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

我读了这个HTML标准cookie厌恶,什么都不懂。

那么,问题是如何将 cookie 推送到从上一个存储的网络驱动程序会话?

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

工作解决方案:

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

只需打开一个标签,添加cookie,然后再次重新打开一个标签

此错误消息...

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

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

<小时 />

详情

根据 HTML 生活标准规范,在以下情况下,Document Object可能被归类为厌恶 cookie 的文档对象:

  • 没有Browsing Context的文档。
  • 其 URL 的方案不是网络方案的文档。
<小时 />

深入探讨

根据无效的 cookie 域,当您访问厌恶 cookie 的文档(例如本地磁盘上的文件)时,可能会发生此错误。

举个例子:

  • 示例代码:
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不能通过Web驱动程序会话推送到任何其他不同的domanin,例如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')
<小时 />

参考

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

  • 将 Cookie 加载到 Python 请求会话时出错

我想你的情况是你在获得带有driver.get('http://mydomain')的网址之前用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.

最新更新