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

标签 python firefox selenium cookies

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

最佳答案

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

Selenium Documentation - 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)

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

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)

关于python - 如何使用 python 在 selenium webdriver 中将 cookie 设置为特定域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24919525/

相关文章:

python - Project Euler 在 python 中获得最小倍数

python - 如何在 Python 中跳过前几行 Excel 工作表

performance - 使用 CSS3 box-shadow 属性滚动滞后?

html - 为什么这个 SVG 蒙版动画在 Firefox 中不连贯,但在 Chrome 中流畅?

wpf - 在 XP 或 Vista/7 上的 VB.NET & WPF 或 WinForms 中向标题栏添加按钮(如 Firefox 4)

python - 用selenium填写登录信息

python - python数据框中的日期时间索引

python - Python 中的 MATLAB spconvert

python - 单击来自 gmail 收件箱 Python 的特定电子邮件

python - Selenium python firefox,禁用图像但显示占位符