Python
Selenium
WebDriver
Cookies
Automation

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.

python
1import json
2from pathlib import Path
3from selenium import webdriver
4
5COOKIE_FILE = Path("cookies.json")
6
7
8def save_cookies(driver, file_path: Path) -> None:
9    cookies = driver.get_cookies()
10    file_path.write_text(json.dumps(cookies, indent=2), encoding="utf-8")
11
12
13driver = webdriver.Chrome()
14driver.get("https://example.com/login")
15
16# Perform the login steps here.
17# After authentication succeeds:
18save_cookies(driver, COOKIE_FILE)
19driver.quit()

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.

python
1import json
2from pathlib import Path
3from selenium import webdriver
4
5COOKIE_FILE = Path("cookies.json")
6
7
8def load_cookies(driver, file_path: Path) -> None:
9    cookies = json.loads(file_path.read_text(encoding="utf-8"))
10    for cookie in cookies:
11        safe_cookie = {
12            key: value
13            for key, value in cookie.items()
14            if key in {"name", "value", "domain", "path", "expiry", "secure", "httpOnly", "sameSite"}
15        }
16        driver.add_cookie(safe_cookie)
17
18
19driver = webdriver.Chrome()
20driver.get("https://example.com")
21load_cookies(driver, COOKIE_FILE)
22driver.refresh()
23driver.quit()

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.

python
1from pathlib import Path
2
3
4class CookieStore:
5    def __init__(self, file_path: Path):
6        self.file_path = file_path
7
8    def exists(self) -> bool:
9        return self.file_path.exists()
10
11    def save(self, driver) -> None:
12        save_cookies(driver, self.file_path)
13
14    def restore(self, driver, base_url: str) -> bool:
15        if not self.exists():
16            return False
17        driver.get(base_url)
18        load_cookies(driver, self.file_path)
19        driver.refresh()
20        return True

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:

  1. try to restore cookies,
  2. verify that the expected authenticated page loads,
  3. 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.

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:

text
cookies.json

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.

Course illustration
Course illustration

All Rights Reserved.