ScreenshotNeo

BlogHow-to

How to Handle Cookies in Selenium WebDriver

Learn to add, inspect, and delete cookies in Selenium WebDriver, with Python, Java, and JavaScript examples, cookie attributes, and troubleshooting tips.

By the ScreenshotNeo team4 October 20267 min read

Selenium WebDriver can add, inspect, and delete cookies for the current browsing context. First navigate to a page on the domain where the cookie should apply, then use the cookie methods provided by your Selenium language binding. A cookie belongs to a site context; trying to add one before opening the relevant domain is a common source of errors.

1. Navigate to the cookie’s domain first

WebDriver cookie commands operate in the current browsing context. Open a page on the domain covered by the cookie before adding or reading it. If the site’s homepage is slow, Selenium’s guide notes that you can navigate to a smaller page on the same site first. See Selenium’s Working with cookies guide.

  1. Create the driver and open a page on the target domain.
  2. Add, inspect, or delete cookies in that browsing context.
  3. Reload or navigate as needed to test how the page behaves with the cookie.

Cookies are scoped by attributes such as domain and path. A cookie set for one domain is not a general browser-wide value you can add from an unrelated page.

2. Python: add, inspect, and delete cookies

These examples use Selenium’s Python WebDriver API. The basic cookie dictionary needs a name and value; additional fields depend on the binding and browser.

from selenium import webdriver

# Ensure the Selenium driver/browser setup for your environment is available.
driver = webdriver.Chrome()
try:
    driver.get("https://example.com/")

    # Add a cookie in the current domain context.
    driver.add_cookie({"name": "session_hint", "value": "example-value"})

    # Read one cookie by name, or inspect the whole cookie set.
    print(driver.get_cookie("session_hint"))
    print(driver.get_cookies())

    # Remove just this cookie.
    driver.delete_cookie("session_hint")

    # Use only when the test intends to clear every cookie in this context.
    driver.delete_all_cookies()
finally:
    driver.quit()

The documented Python method names are add_cookie, get_cookie, get_cookies, delete_cookie, and delete_all_cookies. See the Selenium cookie guide and Python WebDriver API reference for the installed version.

In Java, cookie operations are exposed through driver.manage(). Selenium’s documented examples construct a Cookie and use the returned options interface.

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class CookieExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/");

            driver.manage().addCookie(new Cookie("session_hint", "example-value"));
            Cookie one = driver.manage().getCookieNamed("session_hint");
            System.out.println(one);
            System.out.println(driver.manage().getCookies());

            driver.manage().deleteCookieNamed("session_hint");
            // Clears all cookies in the current context; use deliberately.
            driver.manage().deleteAllCookies();
        } finally {
            driver.quit();
        }
    }
}

Java method placement and signatures differ from Python. Consult Selenium’s language examples and the API reference matching your Selenium dependency.

The JavaScript binding exposes cookie operations through the driver’s manage/options interface. Use a real page on the relevant domain before calling them.

const { Builder } = require('selenium-webdriver');

(async () => {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.get('https://example.com/');

    const options = driver.manage();
    await options.addCookie({ name: 'session_hint', value: 'example-value' });
    console.log(await options.getCookie('session_hint'));
    console.log(await options.getCookies());

    await options.deleteCookie('session_hint');
    // Clears all cookies in the current context; use deliberately.
    await options.deleteAllCookies();
  } finally {
    await driver.quit();
  }
})();

Check the JavaScript binding documentation for the version in your project if a method signature differs. Selenium bindings do not all place methods under the same names.

The simplest cookie is a name/value pair. Selenium’s documentation also shows attributes such as path, secure, and sameSite. Supply attributes that match the site’s behavior and the test you’re writing; exact accepted keys and constructors vary across language bindings and versions.

Field Purpose Practical note
name, value Identify the cookie and its stored value. Required in the basic examples.
path Limits the URL paths where the cookie is sent. Use the path expected by the application.
secure Marks a cookie for secure transport. Test under the same HTTPS conditions as the site.
sameSite Controls cross-site sending behavior. Selenium examples show values including Strict and Lax; browser and binding behavior can vary.

Do not assume every binding accepts identical dictionary keys or builder methods. Refer to the official documentation for your language and installed Selenium version before relying on less common attributes.

6. Common workflows and edge cases

Restore a login state for a test

Navigate to the application’s domain, add the cookie or cookies your test requires, then reload or navigate to the page whose authenticated state you want to inspect. A cookie may not be sufficient to recreate a session if the application also relies on server state or other browser storage.

Inspect before changing state

Use a named-cookie lookup when you know the key. Use get-all when you need to understand the cookie set. Avoid logging sensitive session values in shared CI logs.

Delete narrowly

Delete a named cookie when cleaning up a specific test fixture. Delete all cookies only when the test intends to reset the entire cookie set for the current context; broad cleanup can hide state dependencies or remove cookies another step expects.

Domain and path scope

Open the matching domain before adding. If the cookie is not visible where expected, verify the current URL and the cookie’s domain and path scope. A subdomain and its parent domain may not share cookies unless the cookie’s scope allows it.

Browsers enforce cookie rules in addition to Selenium’s API. Secure transport, same-site policy, expiry, and browser behavior can affect whether a cookie is accepted or sent. Keep tests aligned with the actual browser and site configuration.

7. cURL, Python, and Node.js for a page screenshot

Selenium is appropriate when the test must control a browser session and manipulate browser state. If the task is to capture a page image and does not require your existing Selenium session, a screenshot API can avoid setting up and maintaining a browser driver.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. Make one GET request with the target URL; see the ScreenshotNeo API documentation for options and response details.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const fs = require('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
  • Cookie and consent banners are accepted like a visitor, and more than 60 known consent platforms, newsletter popups, and chat widgets are removed before capture. Each step can be turned off.
  • Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers report the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
  • The free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 screenshots.

Sign up for 1,000 free screenshots a month, with no card.

8. Troubleshooting

Symptom Likely cause Fix
Cookie cannot be added The browser is on a different domain or no page has been opened. Navigate to a page on the cookie’s domain, then add it.
Named lookup returns no cookie The cookie was not accepted, was deleted, or is outside the current domain/path scope. Inspect the current URL and get-all result; check scope and attributes.
Cookie appears but the page remains logged out The application may require additional session state, or the cookie may be expired or invalid. Use a valid test session and reload after adding; confirm the app’s auth flow requirements.
Attribute rejected or constructor error Syntax differs by Selenium binding/version, or the browser rejects the attribute combination. Check the matching official binding documentation and use only supported fields.
Cookie disappears after navigation Its domain or path does not cover the destination, or browser policy prevents use. Set the intended scope and test using the same scheme and domain conditions as production.
Delete-all unexpectedly breaks later steps The test removed cookies required by another action. Delete the specific cookie by name or isolate the test’s browser context.

9. Reliability, performance, and cost

Cookie operations are local WebDriver commands, but page navigation and application behavior usually dominate test time. Navigate once to the correct domain and reuse that context where appropriate. Keep cleanup targeted so a test’s state changes stay understandable.

For reliable automation, pin Selenium and browser versions in your environment, follow the API documentation for that binding, and avoid treating a cookie as proof that the server-side session is still valid. Selenium itself is browser automation software; the examples above do not require a paid screenshot service. ScreenshotNeo pricing, if you choose the screenshot API route, is Free for 1,000 per month, Starter $5 for 3,000, Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000; yearly billing gives two months free, and all features are on every plan.

10. FAQ

Can Selenium read HttpOnly cookies?

WebDriver exposes browser cookie operations, but whether a cookie is available or accepted depends on browser and cookie rules. Check the binding and browser documentation for the specific case.

Should I use cookies or local storage to preserve a test session?

Use the storage mechanism the application actually relies on. WebDriver cookie commands manage cookies; they do not replace local storage or server-side session setup.

It may, if that cookie carries the relevant authentication state. The application can also maintain other state, so verify the behavior in the target app.

Where can I confirm exact method signatures?

Use Selenium’s official cookie guide and the API reference for the language binding and version installed in your project.