p_cos
p_cos

Reputation: 185

Restoring Firefox Session in Selenium

I am currently automating a website and have a test which checks the functionality of the Remember Me option. My test script logs in, entering a valid username and password and checks the Remember Me checkbox before clicking Log In button.

To test this functionality I save the cookies to file using pickle, close the browser and then reopen the browser (loading the cookies file).

def closeWebsite(self, saveCookies=False):
    if saveCookies:
        pickle.dump(self.driver.get_cookies(), open('cookies.pkl', 'wb'))
    self.driver.close()

def openWebsite(self, loadCookies=False):
    desired_caps = {}
    desired_caps['browserName'] = 'firefox'
    profile = webdriver.FirefoxProfile(firefoxProfile)
    self.driver = webdriver.Firefox(profile)
    self.driver.get(appUrl)
    if loadCookies:
        for cookie in pickle.load(open('cookies.pkl', 'rb')):
            self.driver.add_cookie(cookie)

However, when I do this, the new browser is not logged in. I understand that everytime you call the open the browser a new Session is created and this session ID can be obtained using driver.session_id Is it possible, in the openWebsite method to load a driver and specify the sessionID? When I test this manually, the Remember Me option works as expected. I'm just having trouble understanding how Selenium handles this case.

Upvotes: 3

Views: 1343

Answers (1)

Andrew Regan
Andrew Regan

Reputation: 5113

For starters you're loading the page before adding the cookies. Although there is the potential for them to arrive before the page needs / queries them, this isn't correct let alone reliable.

Yet, if you try to set the cookies before any page has loaded you will get an error.

The solution seems to be this:

First of all, 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 and your homepage is large / takes a while to load an alternative is to find a smaller page on the site, [...]

In other words:

  1. Navigate to your home page, or a small entry page on the same domain as appUrl (no need to wait until fully loaded).
  2. Add your cookies.
  3. Load appUrl. From then on you should be fine.

Upvotes: 1

Related Questions