fbpx

Suppose I want to create a Selenium script that logs into Facebook, I would first have to log in to Facebook by instructing Selenium to fill out the login form below

However, instead of spending time to write code for the login ( fill in the form and click on Log in ), I can simply manually login while running Selenium using the Python interactive shell ( or ipython ) and save the cookies after logging in. The code to save the cookies is below:

from selenium import webdriver
import pickle

# open Chrome and navigate to the Facebook login page
driver = webdriver.Chrome()
driver.get("https://facebook.com/login")

# manually login before saving the cookies
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

# exit the browser
driver.quit()

Once the cookies are saved, you can reuse them later for another session with the code below:

from webdriver import selenium
import pickle 

# open Chrome and navigate to Facebook
driver = webdriver.Chrome()
driver.get("https://facebook.com")

# load cookies
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    if 'expiry' in cookie:
        del cookie['expiry']
        driver.add_cookie(cookie)

# reload the page
driver.refresh()