The pickle module in Python implements an essential process for serializing and de-serializing a object structure. Pickling convert the current state of a python object into a byte sequence representation( a sequence will uniquely represent an object). Pickling an/or unpickling is known in other languages as Java - serialization, marshalling, or flattening.

Pickling can convert whole Python object hierarchy into a byte sequences. Unpickling is the reverse operation, converting a byte stream back into an objects. This process has many applications. In this post we will show how to preserve browser session for selenium by saving cookies into pickles and loading the cookies back.

Python pickling and unpickling basic example

Pickling or saving object state to a file is done by:

import pickle

person = {'id':1, 'name':"John", 'title':"mr",'job':"developer"}

pickling_on = open("/home/test/person.pickle","wb")
pickle.dump(person, pickling_on)
pickling_on.close()

pickle_off = open("/home/test/person.pickle","rb")
personOut = pickle.load(pickle_off)
print(personOut)

in the example above we are:

Python saving and loading cookies with pickle

Saving selenium session to cookies is very useful process for many QA-s. In python it's very easy to be done by:

import pickle
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.google.com')
# perform some actions in selenium and save them to a pickle
pickle.dump(driver.get_cookies(), open("/home/test/GoogleCookies.pkl", "wb")) 
  • we are importing the required modules
  • opening new browser and google page
  • do some actions - search, login etc
  • save our browser session in a pickle file

Loading back the cookie information is done by:

import pickle
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.google.com')
#load saved state
for cookie in pickle.load(open("/home/test/GoogleCookies.pkl", "rb")):
    driver.add_cookie(cookie)
# refresh the page
driver.refresh()