Fix Python – How to save and load cookies using Python + Selenium WebDriver

Question

Asked By – Aaron Hiniker

How can I save all cookies in Python’s Selenium WebDriver to a .txt file, and then load them later?

The documentation doesn’t say much of anything about the getCookies function.

Now we will see solution for issue: How to save and load cookies using Python + Selenium WebDriver


Answer

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

import pickle
import selenium.webdriver

driver = 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 pickle
import selenium.webdriver

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

This question is answered By – Ali-Akber Saifee

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0