How to save and load cookies in Selenium?

You can save and load cookies in Selenium using the get_cookies method of the web driver object and the pickle library.

Here is some sample code to save and load cookies while navigating to the ScrapingBee website.

import pickle
from selenium import webdriver

DRIVER_PATH = '/path/to/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)

driver.get("http://www.scrapingbee.com")

# Save cookies
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

# Load cookies
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

Related Selenium web scraping questions: