Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

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

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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...