如何在 goto 之前设置 cookie?

How to set a cookie before the goto?

我在 Watir 6.16.5 和 Selenium 3.142.3 中这样做:

b = Watir::Browser.new(driver)
b.cookies.add('foo', 'Hello, world!', domain: 'www.example.com')
b.goto('http://www.example.com')

我想设置 cookie,然后然后访问网站 cookie 设置。但是,我得到:

Selenium::WebDriver::Error::InvalidCookieDomainError: Document is cookie-averse
            WebDriverError@chrome://marionette/content/error.js:179:5
            InvalidCookieDomainError@chrome://marionette/content/error.js:317:5
            GeckoDriver.prototype.addCookie@chrome://marionette/content/driver.js:2641:11

我做错了什么? This 可能相关,但解决方法是什么?

您必须在同一个域中才能设置 cookie。来自 W3C specs

If the current browsing context’s document element is a cookie-averse Document object, return error with error code invalid cookie domain.

invalid cookie domain

中也有说明

An illegal attempt was made to set a cookie under a different domain than the current page.

解决方法是在域中设置 cookie 后简单地刷新页面

b = Watir::Browser.new(driver)
b.goto('http://www.example.com')
b.cookies.add('foo', 'Hello, world!', domain: 'www.example.com')
b.refresh

您好,我可以在 python 如何处理 cookie 中给出解决方案,希望它能以某种方式帮助您。

获得 cookie 后,您可以将其存储为:

    with open("cookies.pkl","wb") as cookies:
        pickle.dump(driver.get_cookies(),cookies)

注意:存储为pickle文件需要导入pickle

正在检索 Cookie:

def handle_cookies():
    with open("cookies.pkl","rb")as cookies:
        cookie = pickle.load(cookies)
        for ck in cookie:
            driver.add_cookie(ck)

调用此函数时它会处理 cookie