如何使用python将cookie设置为selenium webdriver中的特定域?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24919525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:28:42  来源:igfitidea点击:

How to set a cookie to a specific domain in selenium webdriver with python?

pythonfirefoxseleniumcookies

提问by yanki

Hello fellow StackOverflow users. What I am trying to achieve is prevent annoying helper boxes from popping up when my tests open the main page. So far this is the method I am using to open the main page:

各位 StackOverflow 用户,大家好。我想要实现的是防止在我的测试打开主页时弹出烦人的帮助框。到目前为止,这是我用来打开主页的方法:

def open_url(self, url):
    """Open a URL using the driver's base URL"""
    self.webdriver.add_cookie({'name' : 'tour.index', 'value' : 'complete', 'domain' : self.store['base'] + url})
    self.webdriver.add_cookie({'name' : 'tour.map', 'value' : 'complete', 'domain' : self.store['base'] + url})
    self.webdriver.get(self.store['base'] + url)

However, what returns after I run the test is this:

但是,运行测试后返回的是:

2014-07-23 15:38:19.453057: X Message: u'You may only set cookies for the current domain' ;

How can I set the cookie before I actually load the base testing domain?

如何在实际加载基本测试域之前设置 cookie?

回答by Christian Long

The documentation suggests navigating to a dummy url (such as a 404 page, or the path to an image) before setting the cookies. Then, set the cookies, then navigate to your main page.

该文档建议在设置 cookie 之前导航到一个虚拟 url(例如 404 页面或图像的路径)。然后,设置 cookie,然后导航到您的主页。

Selenium Documentation - Cookies

Selenium 文档 - Cookies

... you need to be on the domain that the cookie will be valid for. If you are trying to preset cookies before you start interacting with a site ... an alternative is to find a smaller page on the site ... (http://example.com/some404page)

...您需要在 cookie 将对其有效的域中。如果您在开始与站点交互之前尝试预设 cookie ......另一种方法是在站点上找到一个较小的页面......(http://example.com/some404page

So, your code might look like this:

因此,您的代码可能如下所示:

def open_url(self, url):
    """Open a URL using the driver's base URL"""

    dummy_url = '/404error'
    # Or this
    #dummy_url = '/path/to/an/image.jpg'

    # Navigate to a dummy url on the same domain.
    self.webdriver.get(self.store['base'] + dummy_url)

    # Proceed as before
    self.webdriver.add_cookie({'name' : 'tour.index', 'value' : 'complete', 'domain' : self.store['base'] + url})
    self.webdriver.add_cookie({'name' : 'tour.map', 'value' : 'complete', 'domain' : self.store['base'] + url})
    self.webdriver.get(self.store['base'] + url)