【问题标题】:How to set a cookie to a specific domain in selenium webdriver with python?如何使用 python 将 cookie 设置为 selenium webdriver 中的特定域?
【发布时间】:2014-09-15 04:06:25
【问题描述】:

您好 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)

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

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

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

【问题讨论】:

    标签: python firefox selenium cookies


    【解决方案1】:

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

    Selenium Documentation - Cookies

    ...您需要位于 cookie 有效的域中。如果你 正在尝试在您开始与网站交互之前预设 cookie ...另一种选择是 在网站上找到一个较小的页面... (http://example.com/some404page)

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

    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)
    

    【讨论】:

    • 为图像设置 cookie 给我一个例外:org.openqa.selenium.UnableToSetCookieException: You may only set cookie on html documents
    • 要添加到此,如果您的 cookie 作为“路径”属性,则浏览器/驱动程序将需要在该路径上才能添加 cookie。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多