Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *