Zimt

Handling Cookies in Selenium WebDriver: A How-To

· 5 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Cookies are small pieces of data that websites store in your browser to remember sessions, preferences, and tracking information. When automating browser tests with Selenium WebDriver, you often need to manage cookies to maintain a logged-in state, test cookie-based features, or ensure a clean slate between test runs. This guide walks you through the essential operations—adding, retrieving, deleting, and updating cookies—using Selenium's built-in API, with code examples in Java (though the concepts translate directly to Python, C#, and other supported languages).

What You'll Need

  • A working Selenium WebDriver setup (e.g., Selenium 4.x) with a language binding installed (Java, Python, etc.).
  • A browser driver (ChromeDriver, GeckoDriver, etc.) that matches your browser version and is on your system PATH.
  • An IDE or text editor to write and run your test script.
  • Basic familiarity with writing and executing Selenium test scripts.

Step-by-Step

  1. Start a browser session. Initialize your WebDriver instance. For example, in Java: WebDriver driver = new ChromeDriver(); This opens a fresh browser window with no cookies by default.
  2. Navigate to the domain you want to work with. Cookies are tied to a domain, so you must be on the correct site before adding or retrieving them. Use driver.get("https://example.com"); and wait for the page to load.
  3. Retrieve all cookies. Call driver.manage().getCookies() to get a set of Cookie objects. Each has methods like getName(), getValue(), getDomain(), getPath(), and getExpiry(). Iterate through them to inspect what the site has set.
  4. Get a specific cookie by name. Use driver.manage().getCookieNamed("session_id") to fetch a single cookie. This returns null if the cookie doesn't exist.
  5. Add a new cookie. Create a Cookie object with new Cookie("name", "value") (optionally include domain, path, expiry, and secure flags) and then call driver.manage().addCookie(cookie). The cookie will be stored for the current domain.
  6. Delete a specific cookie. Use driver.manage().deleteCookieNamed("cookieName") to remove it by name, or driver.manage().deleteCookie(cookie) if you have the Cookie object.
  7. Delete all cookies. Call driver.manage().deleteAllCookies() to clear the entire cookie jar. This is useful for logging out or resetting state between tests.
  8. Update an existing cookie. Selenium does not have an “update” method. Instead, delete the old cookie and add a new one with the same name but a different value or attributes. For example: driver.manage().deleteCookieNamed("theme"); driver.manage().addCookie(new Cookie("theme", "dark"));
  9. Persist cookies across test runs. To reuse a session, save the cookies to a file after login, then load them in a later session. Serialize each cookie's name, value, domain, path, expiry, and secure flag, then recreate them with addCookie() after navigating to the same domain.

Common Mistakes

  • Adding cookies before navigating to the domain. The browser will reject cookies that don't match the current domain. Always load the site first.
  • Forgetting to wait for the page to load. If you add a cookie immediately after get(), the page might not be ready, and the cookie may not stick. Use implicit or explicit waits.
  • Assuming cookies are shared across browser windows. Each WebDriver instance has its own isolated browser profile, so cookies are not shared between different driver sessions.
  • Ignoring the secure flag. If a cookie is marked Secure, it will only be sent over HTTPS. Adding it on an HTTP page may fail silently.
  • Not handling expiry dates. When recreating cookies, if you don't set the expiry, the cookie becomes a session cookie and disappears when the browser closes.

Tips

  • Use deleteAllCookies() in your test setup to ensure a clean state, especially when running tests in sequence.
  • For login flows, capture cookies after authentication and reuse them to speed up tests that don't need to test login itself.
  • When testing cookie-related features, verify the cookie's attributes (expiry, domain, path) to ensure they match the expected behavior.
  • In Selenium 4, the Cookie class has a builder pattern in some languages (e.g., new Cookie.Builder("name", "value").domain("example.com").build()) for more readable code.
  • Always close the driver (driver.quit()) in a finally block to release resources and avoid leaving background processes.

Troubleshooting

  • Cookie not being added. Check that you are on the correct domain and that the cookie's path is valid (default is “/”). Also ensure the cookie's secure flag matches the protocol (HTTPS vs HTTP).
  • getCookieNamed returns null. The cookie may have expired, or you might be on a different domain/subdomain. Use getCookies() to list all cookies and verify the name.
  • Cookie disappears after page refresh. If the cookie is a session cookie (no expiry), it will be lost when the browser closes. If it disappears on refresh, the server may be deleting it; check the server's response headers.
  • Cannot delete a cookie. Some cookies are HttpOnly, meaning they can't be accessed via JavaScript, but Selenium can still delete them. If deletion fails, ensure the cookie name is correct and you're on the same domain.
  • Tests fail when reusing cookies. Cookies may have expired or the session may have been invalidated on the server. Refresh the cookies by logging in again.

Frequently Asked Questions

How do I set a cookie with an expiration date?

Use the Cookie constructor that accepts a Date object for expiry. For example, in Java: new Cookie("name", "value", "/", null, new Date(System.currentTimeMillis() + 86400000)) sets a cookie that expires in 24 hours.

Can I use Selenium to read HttpOnly cookies?

Yes, Selenium WebDriver can access HttpOnly cookies through the driver's cookie API, unlike JavaScript which cannot. This is useful for testing session management.

How do I handle cookies in headless mode?

Headless browsers (like Chrome headless) support cookies the same way. Just ensure you configure the driver options correctly (e.g., --headless) and follow the same steps.

Is it possible to share cookies between two WebDriver instances?

Not directly. Each instance has its own isolated profile. You can export cookies from one and import them into another by serializing and deserializing them.

What happens to cookies when I call driver.quit()?

All cookies are lost because the browser session is terminated. If you need to persist them, save them to a file before quitting.

Can I add a cookie for a different domain than the current one?

No, the browser will reject it. You must navigate to that domain first, then add the cookie.