Explain Codes LogoExplain Codes Logo

How to save and load cookies using Python + Selenium WebDriver

python
selenium
webdriver
cookies
Anton ShumikhinbyAnton Shumikhin·Feb 20, 2025
TLDR

To persist browser cookies in your Selenium WebDriver sessions, you can save and load cookies from a JSON file. driver.get_cookies() after login lets you fetch cookies to store in a JSON file. When reconnecting to the site, you can load cookies back from this file using driver.add_cookie() ensuring continuity of your session:

from selenium import webdriver import json # Save cookies driver = webdriver.Chrome() # Chrome: The speedy browser driver.get('https://example.com/login') # Assume magic happens and you log in here cookies = driver.get_cookies() with open('cookies.json', 'w') as f: json.dump(cookies, f) # Voila! Your cookies are stashed away # Load cookies driver = webdriver.Chrome() # Chrome: Again, the speedy browser is back driver.get('https://example.com') with open('cookies.json', 'r') as f: cookies = json.load(f) for cookie in cookies: driver.add_cookie(cookie) # Cookies to the rescue driver.refresh() # Presto! You're logged back in, thanks to cookies

Modify 'https://example.com/login' and 'https://example.com' according to your needs. This approach heavily leans on JSON for its simplicity and readability.

Utilizing pickle for better serialization

Typically, pickle is the more flexible option, useful when you have non-JSON serializable types like datetime:

import pickle # Save cookies using pickle with open('cookies.pkl', 'wb') as f: pickle.dump(driver.get_cookies(), f) # Pickle jar for cookies # Load cookies using pickle with open('cookies.pkl', 'rb') as f: cookies = pickle.load(f) for cookie in cookies: driver.add_cookie(cookie) # Cookies are back with a pickle

Security tip: Never unpickle data from an untrusted source, as it gives hackers a welcome mat.

Working with different browsers and browser options

# Firefox driver = webdriver.Firefox() # Firefox: For the browser switchers

Switch webdriver.Chrome() with webdriver.Firefox(). Selenium spies no difference between the two.

To manage cookies in separate user profiles using Chrome:

from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--user-data-dir=/path/to/your/custom/profile") # pigeon-hole browser profiles driver = webdriver.Chrome(chrome_options=options) # Kudos for organized cookies

Security considerations and best practices

Tread on the side of caution

Remember, your browser communicates session-specific sensitive data in cookies. Make sure interactions happen via secure HTTPS:

driver.get('https://secure-website.com') # HTTPS: The 'S' stands for 'Secure'

End sessions gracefully

Ending a session is more than just closing a browser window. Call driver.quit() to terminate the WebDriver session properly:

driver.quit() # Driver. thank you for the ride!

Troubleshooting

Timing issues

Use time.sleep() to pause execution and allow pages to load:

import time time.sleep(2) # Shh! The machine is sleeping!

WebDriver path issues

If your chromedriver.exe isn't within system PATH, don't fret. You can specify the path directly in code:

driver = webdriver.Chrome(executable_path='/path/to/chromedriver') # No PATH, no problem!

Websites preferring familiar faces

Some websites only set cookies after an initial visit. A driver.get() before adding cookies solves this:

driver.get('https://website-requiring-prior-visit.com') # Break the ice, then add cookies