How to save and load cookies using Python + Selenium WebDriver How to save and load cookies using Python + Selenium WebDriver python python

How to save and load cookies using Python + Selenium WebDriver


You can save the current cookies as a Python object using pickle. For example:

import pickleimport selenium.webdriverdriver = selenium.webdriver.Firefox()driver.get("http://www.google.com")pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

And later to add them back:

import pickleimport selenium.webdriverdriver = selenium.webdriver.Firefox()driver.get("http://www.google.com")cookies = pickle.load(open("cookies.pkl", "rb"))for cookie in cookies:    driver.add_cookie(cookie)


When you need cookies from session to session, there is another way to do it. Use the Chrome options user-data-dir in order to use folders as profiles. I run:

# You need to: from selenium.webdriver.chrome.options import Optionschrome_options = Options()chrome_options.add_argument("user-data-dir=selenium") driver = webdriver.Chrome(chrome_options=chrome_options)driver.get("www.google.com")

Here you can do the logins that check for human interaction. I do this and then the 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.

The second time I run, all the cookies are there:

# You need to: from selenium.webdriver.chrome.options import Options    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, etc., 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.


Remember, you can only add a cookie for the current domain.

If you want to add a cookie for your Google account, do

browser.get('http://google.com')for cookie in cookies:    browser.add_cookie(cookie)