Python selenium: use a browser that is already open and logged in with login credentials

Well, since this question is upvoted but my flag as duplicated question wasn't accepted I will post here the same exact answer I already posted for a similar question:


You can use pickle to save cookies as text file and load it after:

def save_cookie(driver, path):
    with open(path, 'wb') as filehandler:
        pickle.dump(driver.get_cookies(), filehandler)

def load_cookie(driver, path):
     with open(path, 'rb') as cookiesfile:
         cookies = pickle.load(cookiesfile)
         for cookie in cookies:
             driver.add_cookie(cookie)

With a script like:

from selenium import webdriver
from afile import save_cookie

driver = webdriver.Chrome()
driver.get('http://website.internets')

foo = input()

save_cookie(driver, '/tmp/cookie')

What you can do is:

  1. Run this script
  2. On the (selenium's) browser, go to the website, login
  3. Go back to your terminal, type anything hit enter.
  4. Enjoy your cookie file at /tmp/cookie. You can now copy it into your code repo and package it into your app if needed.

So, now, in your main app code:

from afile import load_cookie

driver = webdriver.Chrome()
load_cookie(driver, 'path/to/cookie')

And you are now logged.


This was a feature request and closed as not feasible. But is a way to do it, use folders as profiles and keep all logins persistent from session to session by using the Chrome options user-data-dir in order to use folders as profiles, I run:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

You can manually interact at this step with the opened window and do the logins that check for human interaction, check remember password etc I do this and then the logins, cookies I need now every-time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session. Second time I run, with exactly the same code as above, all the settings, cookies and logins are there:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") #Now you can see  the cookies, the settings, Extensions and the logins done in the previous session are present here

The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc Also this is faster than having to do it all by code.


I had a exact same 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/username/work/chrome/chromedriver',
        # pickle file path to store cookies
        cookies_file_path='/Users/username/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 __del__(self):
        self.save_cookies()
        self.close_all()


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)

    del selenium_object

Run 1: Login & Save Cookies

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

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

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