Storing and retrieving session after login with Python Selenium

A simple example by which you can get the cookies from the webdriver and pickle them and save the pickle in a file; for loading cookies you can unpickle the saved file data and add the cookies to the driver as shown on below code sample.

Getting and Storing Cookies

import pickle
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://phpfarmer.com')
# login code
pickle.dump(driver.get_cookies() , open("PHPCookies.pkl","wb"))

Loading Cookies

import pickle
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://phpfarmer.com')
for cookie in pickle.load(open("PHPCookies.pkl", "rb")):
    driver.add_cookie(cookie)

Very simple, isn’t it?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: