PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To keep a Selenium login between runs, save the cookie dictionaries returned by driver.get_cookies() after logging in. In the next run, open a page on the cookie’s domain, add each saved cookie with driver.add_cookie(), then refresh or navigate to the page you need. This guide shows a complete Python workflow, explains cookie scope and common failures, and covers safe handling of the saved session data.
Save Selenium cookies after login
Selenium’s get_cookies() returns a list of dictionaries for cookies visible in the current WebDriver context. Save that list as JSON so each cookie’s attributes remain available for restoration. The file contains authentication material: anyone who can use a still-valid session cookie may be able to act as the logged-in user.
Complete Python example
Install Selenium if it is not already in your environment with python -m pip install selenium. Selenium Manager can manage supported browser drivers for many standard setups; your browser still needs to be installed and compatible. Replace the example URL and login steps with those for your own application.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →import json
from pathlib import Path
from selenium import webdriver
COOKIE_FILE = Path("cookies.json")
BASE_URL = "https://example.com/"
def save_cookies(driver):
cookies = driver.get_cookies()
with COOKIE_FILE.open("w", encoding="utf-8") as file:
json.dump(cookies, file, indent=2)
print(f"Saved {len(cookies)} cookies to {COOKIE_FILE}")
def load_cookies(driver):
# Selenium must be on the cookie's domain before adding it.
driver.get(BASE_URL)
with COOKIE_FILE.open(encoding="utf-8") as file:
cookies = json.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
# Make a request with the restored cookies.
driver.refresh()
with webdriver.Chrome() as driver:
# First run: open the site, complete its normal login, then save.
driver.get(BASE_URL)
# Perform your login steps here.
# save_cookies(driver)
# Later run: call load_cookies(driver) instead, then continue.
# load_cookies(driver)
For the first run, uncomment save_cookies(driver) after the login has completed. For a later run, use load_cookies(driver) and leave the interactive login steps out. Don’t call both blindly: a login flow may redirect or change the state you are trying to restore. The example opens the base URL before importing because the browser must first be at a matching domain.
#1 Best Overall
Save only after authentication is established
Wait for a reliable post-login signal before exporting cookies, such as a user menu or an authenticated page element. If you save too early, the file may contain only pre-login cookies. Some sites also complete authentication through redirects or establish additional session state after the initial form submission; verify that the browser is actually logged in before writing the file.
Load cookies in a later browser session
- Start the browser. Create the WebDriver session you will use for the automation.
- Open a page on the right domain. Navigate to a URL on the cookie’s domain before calling
add_cookie(). The Selenium guide says the browser must first be on the domain for which the cookie is valid. - Read the saved JSON. Parse the complete list of cookie dictionaries from the file.
- Add each cookie. Pass each dictionary to
driver.add_cookie(cookie). Selenium requiresnameandvalue; optional documented keys includepath,domain,secure,httpOnly, andsameSite. - Refresh or navigate. Refresh the current page or open the page that needs the authenticated state so the browser makes a request using the restored cookies.
- Confirm the result. Check an authenticated page or element rather than assuming that adding cookies guarantees a valid login.
If the homepage is slow or has side effects, Selenium’s guide suggests opening a smaller page on the same site, such as a 404 page, to establish the domain before adding cookies. Choose a URL that is still within the cookie’s valid scope.
Why cookie domain and attributes matter
A cookie is not simply a username-and-password substitute. Its domain and path determine where it applies; secure affects whether it is sent over an appropriate secure connection; and attributes such as httpOnly and sameSite describe additional browser behavior. Keep the complete dictionaries returned by Selenium unless you have a specific reason to change one.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
- Domain: A cookie for one host may not be valid for a different host or subdomain. Start on the relevant domain and do not assume a cookie from
www.example.comcan be used on another host. - Path: A cookie restricted to a path may not be sent to a URL outside that path.
- Secure: Secure cookies should be used with HTTPS. Testing on plain HTTP can make a valid saved cookie appear ineffective.
- Expiry: Expired cookies cannot restore a session. Session cookies may not be useful after the browser session ends, depending on the site and how it issued them.
- Site-specific state: Some authentication flows rely on more than cookies, or reject sessions when other conditions change. Cookie import is not a universal way to bypass a site’s login or security checks.
Persisting the browser’s full cookie dictionaries preserves attributes that can affect acceptance and scope. Blindly stripping fields or replaying a cookie list against another environment can change its behavior or cause rejection.
Inspect, remove, and validate cookies
Use Selenium’s cookie methods to diagnose what the current browser context can see:
driver.get_cookies()returns all cookies visible in the current WebDriver context.driver.get_cookie("name")looks up one cookie. The Edge Python API documents a cookie dictionary when a match exists, orNonewhen it does not.driver.delete_cookie("name")removes one cookie.driver.delete_all_cookies()clears cookies in the session scope.
These methods help distinguish “the cookie was never restored” from “the cookie was restored but the site did not accept the session.” After import, inspect the current cookies if necessary, then check the site’s authenticated state. Do not print or log full cookie values in shared test logs.
Rank #3
Common failures and fixes
add_cookie fails or rejects a dictionary
Make sure the current page is on the cookie’s domain before adding it. Check that each dictionary has the required name and value, and retain Selenium’s returned attributes rather than inventing or renaming keys. A cookie saved for a different host or path may not be accepted in the current context.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →The script runs, but the browser is still logged out
Confirm that the file was created after a successful login and contains cookies, and that the next run loaded that file. Verify the cookie’s domain, path, and expiry; use HTTPS for secure cookies. Then refresh or navigate to the protected page. If the site rejects the session or its authentication depends on other state, complete the normal login flow again and save a fresh set.
The cookie file is missing or invalid JSON
Ensure the script is reading the same path it wrote. A relative path such as cookies.json is resolved from the process’s current working directory, which may differ when a test runner launches the script. Use an explicit path if needed, and write the file only after get_cookies() has returned successfully.
Rank #4
Cookies work on one host but not another
Do not assume portability across domains, subdomains, staging and production, or separate browser environments. Inspect the saved domain and path, open a matching URL, and use a newly authenticated cookie set for the target environment.
A session stops working later
Cookies may expire, be rotated, or be invalidated by the site. Treat a saved file as a temporary session snapshot, not permanent credentials. When it is rejected, run the site’s normal login process and replace the saved data.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsProtect cookie files and parallel tests
Cookie JSON can grant access to a live account, so keep it out of source control, public build artifacts, screenshots, and untrusted logs. Restrict file permissions and delete the file when it is no longer needed. For automated tests, use a dedicated test account and follow the application owner’s rules for session reuse.
Best Value
Parallel runs need special care: if multiple tests read and rewrite one cookie file, they can overwrite one another or use sessions in inconsistent states. Give independent runs separate files or generate their authenticated state independently. Cookie export/import is portable as data, but the session itself is governed by the site and may be invalidated or bound to conditions beyond the saved dictionary.
When cookie persistence is the right approach
Saving cookies is useful when a controlled automation task needs to avoid repeating a login flow between runs and the site permits that reuse. It is not a substitute for a proper test authentication strategy when the application provides one, and it should not be used to evade access controls. Keep login and recovery logic available: a rejected or expired session should lead to a normal reauthentication path, not endless retries with stale data.
Or skip the browser setup
If the task is to capture a page rather than automate an authenticated workflow, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. One GET request can return a PNG, JPEG, WebP, or PDF; it is not a Selenium cookie-persistence replacement, and this example captures a public URL.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for request options. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.
Frequently Asked Questions
Does Selenium save cookies automatically between runs?
No. A new WebDriver session does not automatically load a cookie file from a previous run; export and restore the cookies explicitly.
Can I use saved cookies to avoid every login?
Not reliably. A site can expire, rotate, or reject a session, and some authentication flows depend on state beyond the cookie list.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

