Cookie state decides whether a Selenium test sees a first-visit page, a remembered preference, or an authenticated application path. Old cookies from a previous scenario and cookies added on the wrong domain can both send the browser through the wrong branch, so cookie setup belongs beside the test action that depends on it.
Selenium WebDriver exposes browser cookies through methods on the active browsing context. In Python, add_cookie() inserts a cookie for the current domain, get_cookie() and get_cookies() inspect stored values, and delete_cookie() or delete_all_cookies() reset browser state.
Navigate to the target host before adding a cookie, then refresh or make another request before expecting the page or server to use it. Use controlled fixture cookies for tests, and avoid creating production authentication cookies outside the application's approved login or test-token flow.
$ cat > selenium-cookies-manage.py <<'PY'
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from shutil import which
from threading import Thread
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
class CookieDemoHandler(BaseHTTPRequestHandler):
def do_GET(self):
cookie_header = self.headers.get("Cookie", "(none)")
body = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Selenium cookie demo</title>
</head>
<body>
<p id="cookie-header">{cookie_header}</p>
</body>
</html>
"""
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(body.encode("utf-8"))
def log_message(self, format, *args):
return
server = ThreadingHTTPServer(("127.0.0.1", 0), CookieDemoHandler)
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
options = Options()
options.add_argument("--headless=new")
chrome_binary = which("chromium") or which("chromium-browser") or which("google-chrome")
if chrome_binary:
options.binary_location = chrome_binary
chromedriver = which("chromedriver")
service = Service(chromedriver) if chromedriver else None
driver = (
webdriver.Chrome(service=service, options=options)
if service
else webdriver.Chrome(options=options)
)
try:
driver.get(f"http://127.0.0.1:{server.server_port}/")
driver.delete_all_cookies()
print(f"Initial cookie count: {len(driver.get_cookies())}")
driver.add_cookie({
"name": "session_id",
"value": "qa-12345",
"path": "/",
"sameSite": "Lax",
})
saved_cookie = driver.get_cookie("session_id")
print(
"Saved cookie: "
f"name={saved_cookie['name']} "
f"value={saved_cookie['value']} "
f"sameSite={saved_cookie.get('sameSite')}"
)
driver.refresh()
cookie_header = driver.find_element(By.ID, "cookie-header").text
assert cookie_header == "session_id=qa-12345"
print(f"Request Cookie header: {cookie_header}")
driver.delete_cookie("session_id")
driver.refresh()
cookie_header = driver.find_element(By.ID, "cookie-header").text
assert cookie_header == "(none)"
print(f"After delete_cookie: {cookie_header}")
driver.add_cookie({"name": "cart", "value": "empty", "path": "/"})
driver.add_cookie({"name": "theme", "value": "dark", "path": "/"})
print(f"Cookie count before delete_all_cookies: {len(driver.get_cookies())}")
driver.delete_all_cookies()
print(f"Cookie count after delete_all_cookies: {len(driver.get_cookies())}")
finally:
driver.quit()
server.shutdown()
PY
The local page gives add_cookie() a real domain context, and the refresh proves the browser sends the cookie back as an HTTP Cookie header.
$ python3 selenium-cookies-manage.py Initial cookie count: 0 Saved cookie: name=session_id value=qa-12345 sameSite=Lax Request Cookie header: session_id=qa-12345 After delete_cookie: (none) Cookie count before delete_all_cookies: 2 Cookie count after delete_all_cookies: 0
driver.get("https://app.example.com/health")
driver.delete_all_cookies()
driver.add_cookie({
"name": "session_id",
"value": "qa-12345",
"path": "/",
"sameSite": "Lax",
})
driver.refresh()
Omit domain unless the test needs a parent-domain cookie. WebDriver rejects cookies whose domain does not match the current browser URL.
session_cookie = driver.get_cookie("session_id")
assert session_cookie["value"] == "qa-12345"
assert session_cookie["sameSite"] == "Lax"
driver.delete_cookie("session_id")
driver.delete_all_cookies()
Clearing all cookies removes consent, preference, authentication, and tracking state for the current browser session. Run it before a scenario starts, not halfway through a flow that depends on those values.
$ rm selenium-cookies-manage.py