How to save and load cookies using Python Selenium WebDriver
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Saving and restoring cookies in Selenium is a practical way to avoid logging in on every test run, provided the application allows session reuse. The two important rules are: save cookies only after a real authenticated session exists, and restore them only after the browser has opened a page on the matching domain.
Save Cookies After Login
Selenium exposes cookies as ordinary dictionaries, which makes JSON a convenient storage format.
This keeps the saved session state human-readable and easy to inspect when something goes wrong.
Restore Cookies in a New Browser Session
When restoring cookies, Selenium requires the browser to already be on the correct domain. You cannot add cookies for example.com while the browser is still on about:blank or another site.
After the refresh, the browser sends the restored cookies and many sites will resume the session automatically.
Wrap the Logic in a Helper
If several tests share this pattern, a small helper keeps the logic centralized.
This makes it easier to swap in a fallback login flow when the cookies are missing or expired.
Cookies Are Not Magic Authentication Bypass Tokens
Restored cookies do not guarantee success forever. Sessions may expire, servers may rotate tokens, and some systems bind sessions to other signals such as user agent, IP, or server-side session state.
That means a robust automation flow usually works like this:
- try to restore cookies,
- verify that the expected authenticated page loads,
- fall back to interactive login if the session is no longer valid.
Cookie restoration is a convenience optimization, not a permanent substitute for authentication logic.
Treat Cookie Files as Secrets
Cookie files often contain active session data. Do not commit them to source control, and do not leave them carelessly on shared machines.
A simple .gitignore entry is a good start:
If the automation runs in CI, prefer a short-lived storage path and clean it up when the run finishes.
Common Pitfalls
A common mistake is calling add_cookie before navigating to the target domain. Selenium rejects that because cookie scope is domain-specific.
Another issue is assuming an expired or invalidated session means Selenium is broken. Often the site is simply refusing old cookies, which is expected behavior.
Teams also forget that cookies are sensitive data. A stored session file can be equivalent to a live login.
Summary
- Save cookies only after a successful authenticated session exists.
- Restore cookies only after opening a page on the correct domain.
- Store the cookie data in JSON for easy debugging and reuse.
- Treat cookie files as secrets because they often grant active session access.
- Build a fallback login path because restored sessions eventually expire.

