How to save and load cookies using Python and Selenium WebDriver?

Sometimes, we want to save and load cookies using Python and Selenium WebDriver.

In this article, we’ll look at how to save and load cookies using Python and Selenium WebDriver.

How to save and load cookies using Python and Selenium WebDriver?

To save and load cookies using Python and Selenium WebDriver, we can save and get cookies with pickle.

For instance, we write

import pickle
import selenium.webdriver

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

to call pickle.dump with the cookies we get from driver.get_cookies.

And then we get the saved cookie with pickle.load by writing

import pickle
import selenium.webdriver

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

We call pickle.load with the opened pickle file to load the cookies.

And then we call driver.add_cookie to add the cookie into the opened page.

Conclusion

To save and load cookies using Python and Selenium WebDriver, we can save and get cookies with pickle.