DEV Community

Cover image for Reuse sessions using cookies in python selenium
Hardik Sondagar
Hardik Sondagar

Posted on • Updated on

Reuse sessions using cookies in python selenium

I have a scenario where I would like to reuse once authenticated/logged-in sessions. I'm using multiple browser simultaneously.

I've tried plenty of solutions from blogs and StackOverflow answers.

1. Using user-data-dir and profile-directory

These chrome options which solves purpose if you opening one browser at a time, but if you open multiple windows it'll throw an error saying user data directory is already in use.

2. Using cookies

Cookies can be shared across multiple browsers. Code available in SO answers are have most of the important blocks on how to use cookies in selenium. Here I'm extending those solutions to complete the flow.

Code

# selenium-driver.py
import pickle
from selenium import webdriver


class SeleniumDriver(object):
    def __init__(
        self,
        # chromedriver path
        driver_path='/Users/hardiksondagar/work/chrome/chromedriver',
        # pickle file path to store cookies
        cookies_file_path='/Users/hardiksondagar/work/chrome/cookies.pkl',
        # list of websites to reuse cookies with
        cookies_websites=["https://facebook.com"]

    ):
        self.driver_path = driver_path
        self.cookies_file_path = cookies_file_path
        self.cookies_websites = cookies_websites
        chrome_options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(
            executable_path=self.driver_path,
            options=chrome_options
        )
        try:
            # load cookies for given websites
            cookies = pickle.load(open(self.cookies_file_path, "rb"))
            for website in self.cookies_websites:
                self.driver.get(website)
                for cookie in cookies:
                    self.driver.add_cookie(cookie)
                self.driver.refresh()
        except Exception as e:
            # it'll fail for the first time, when cookie file is not present
            print(str(e))
            print("Error loading cookies")

    def save_cookies(self):
        # save cookies
        cookies = self.driver.get_cookies()
        pickle.dump(cookies, open(self.cookies_file_path, "wb"))

    def close_all(self):
        # close all open tabs
        if len(self.driver.window_handles) < 1:
            return
        for window_handle in self.driver.window_handles[:]:
            self.driver.switch_to.window(window_handle)
            self.driver.close()

    def quit(self):
        self.save_cookies()
        self.close_all()
        self.driver.quit()



def is_fb_logged_in():
    driver.get("https://facebook.com")
    if 'Facebook – log in or sign up' in driver.title:
        return False
    else:
        return True


def fb_login(username, password):
    username_box = driver.find_element_by_id('email')
    username_box.send_keys(username)

    password_box = driver.find_element_by_id('pass')
    password_box.send_keys(password)

    login_box = driver.find_element_by_id('loginbutton')
    login_box.click()


if __name__ == '__main__':
    """
    Run  - 1
    First time authentication and save cookies

    Run  - 2
    Reuse cookies and use logged-in session
    """
    selenium_object = SeleniumDriver()
    driver = selenium_object.driver
    username = "fb-username"
    password = "fb-password"

    if is_fb_logged_in(driver):
        print("Already logged in")
    else:
        print("Not logged in. Login")
        fb_login(username, password)

    selenium_object.quit()
Enter fullscreen mode Exit fullscreen mode

Run 1: Login & Save Cookies

$ python selenium-driver.py
[Errno 2] No such file or directory: '/Users/hardiksondagar/work/chrome/cookies.pkl'
Error loading cookies
Not logged in. Login
Enter fullscreen mode Exit fullscreen mode

This will open facebook login window and enter username-password to login. Once logged-in it'll close the browser and save cookies.

Run 2: Reuse cookies to continue loggedin session

$ python selenium-driver.py
Already logged in
Enter fullscreen mode Exit fullscreen mode

This will open logged in session of facebook using stored cookies.

Requirements

  • Python 3.7
  • Selenium Webdriver
  • Pickle

Discussion (1)

Collapse
hnljq profile image
hnljq

the code for facebook is no problem entirely , but when I try to login other websites like "atlassian.com/software/confluence" , add_cookie failed to get logged status, until I delete all cookie before log in . then add cookie from file. so maybe it's more general for logging in more websites