小编典典

org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie

selenium

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

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

我阅读了此HTML Standard
Cookie规章
,一点也不懂。

因此,问题是如何将cookie推送到上一个存储的webdriver会话中?


阅读 1164

收藏
2020-06-26

共1个答案

小编典典

此错误消息…

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.comcookie, 则无法 通过webdriver会话将这些存储的cookie
推送到任何其他不同的域,例如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')

2020-06-26