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

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


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)