How to save and load cookies using Python + Selenium WebDriver
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:
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:
Security tip: Never unpickle data from an untrusted source, as it gives hackers a welcome mat.
Working with different browsers and browser options
Switch webdriver.Chrome()
with webdriver.Firefox()
. Selenium spies no difference between the two.
To manage cookies in separate user profiles using Chrome:
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:
End sessions gracefully
Ending a session is more than just closing a browser window. Call driver.quit()
to terminate the WebDriver session properly:
Troubleshooting
Timing issues
Use time.sleep()
to pause execution and allow pages to load:
WebDriver path issues
If your chromedriver.exe
isn't within system PATH, don't fret. You can specify the path directly in code:
Websites preferring familiar faces
Some websites only set cookies after an initial visit. A driver.get()
before adding cookies solves this:
Was this article helpful?