📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

Handling Cookies in Selenium: Complete Guide with Examples

Azma Banu
Learn how to manage, add, delete, and troubleshoot cookies in Selenium WebDriver with practical examples and best practices for real device testing.
Handling Cookies in Selenium_ Complete Guide with Examples

Cookies are small pieces of data stored by a web browser that can hold information about a user’s session or preferences. In web automation testing, managing cookies is crucial because they help simulate user sessions, manage authentication, and track user activity.

This article will walk you through handling cookies in Selenium WebDriver, providing best practices, common operations, and troubleshooting tips.

Understanding Cookies in Selenium

Here are types of cookies and how they work:

Types of Cookies: Session vs Persistent

In Selenium, cookies can be broadly categorized into two types:

  • Session Cookies: These cookies are temporary and are deleted once the browser session ends. They store session-specific data like authentication information or user preferences during a single browsing session.
  • Persistent Cookies: These cookies have an expiration date and are stored even after the browser is closed. They can be used to remember users across multiple sessions.

How Browsers Store and Handle Cookies?

Browsers store cookies in a local file or memory, depending on whether they are persistent or session cookies. Selenium WebDriver provides methods to interact with and manipulate cookies stored by the browser.

Working with Cookies in Selenium

Here are some ways:

Accessing Cookies in Selenium WebDriver

To access cookies in Selenium, you can use the getCookies() method, which returns all cookies as a list of Cookie objects.

Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + " = " + cookie.getValue());
}

Adding Cookies to the Browser Session

Adding cookies to a session is useful for handling login tests, where you might want to add a pre-existing authentication cookie.

Cookie cookie = new Cookie("name", "value");
driver.manage().addCookie(cookie);

Deleting Specific Cookies

If you need to delete a specific cookie, use the deleteCookieNamed() method by providing the cookie’s name.

driver.manage().deleteCookieNamed("cookieName");

Clearing All Cookies

To clear all cookies for the current browser session, use:

driver.manage().deleteAllCookies();

Common Cookie Operations in Selenium

Checking Cookie Existence

You can check if a cookie exists by using the getCookieNamed() method, which retrieves the cookie by its name. If the cookie exists, it returns the cookie; otherwise, it returns null.

Cookie cookie = driver.manage().getCookieNamed("cookieName");
if (cookie != null) {
System.out.println("Cookie exists: " + cookie.getValue());
}
else {
System.out.println("Cookie not found");
}

Retrieving Cookie Values

Once you retrieve a cookie, you can access its properties like name, value, domain, expiry, and more.

Cookie cookie = driver.manage().getCookieNamed("cookieName");
System.out.println("Cookie value: " + cookie.getValue());

Modifying Cookies in Selenium

To modify a cookie, you can delete it and then add a new one with the updated values:

driver.manage().deleteCookieNamed("cookieName");
Cookie newCookie = new Cookie("cookieName", "newValue");
driver.manage().addCookie(newCookie);

Handling Cookies Across Multiple Browser Sessions

Here are ways to handle cookies across multiple browsers sessions:

Preserving Cookies for Future Sessions

You can preserve cookies by saving them to a file and loading them back for future test sessions. This helps in scenarios where you need to maintain the state between tests, like staying logged in.

  • Save Cookies: After performing an action like logging in, you can save the cookies to a file:
Set<Cookie> cookies = driver.manage().getCookies();
// Code to serialize cookies to a file
  • Load Cookies: For the next session, load the cookies back into the browser:
// Deserialize cookies from the filefor (Cookie cookie : cookies) {
driver.manage().addCookie(cookie);
}

Sharing Cookies Across Different Test Suites

Sharing cookies across test suites can be done by exporting the cookies after one suite and importing them in another. This method can be useful when your tests need to maintain session consistency across multiple suites.

Best Practices for Handling Cookies in Selenium

Here are some best practices for handling cookies in Selenium:

  • Avoiding Flaky Tests with Cookie Management: To avoid flaky tests, make sure to handle cookies appropriately, especially when dealing with authentication. Always ensure that cookies are loaded before executing tests that depend on them.
  • Managing Cookies in Headless Browsers: When running tests in headless browsers (like Chrome or Firefox in headless mode), ensure that cookies are being set and retrieved correctly. Sometimes, headless environments might have different behaviors, so it’s important to test cookies in both headless and regular browser modes.
  • Security Considerations when Using Cookies: While working with cookies, especially authentication cookies, ensure sensitive information like session tokens is protected. Avoid storing cookies with personal or sensitive data in logs, and use secure mechanisms (such as SSL/TLS) to handle cookies.

Troubleshooting Cookie Issues in Selenium

Here are the common errors when working with cookies:

  • Cookie Not Found: This error typically occurs when the cookie you are trying to access doesn’t exist in the current session. Double-check the cookie name and the timing of cookie retrieval.
  • Cookie Not Being Set: If cookies aren’t being set, ensure that your browser allows cookies and the cookie domain is correctly specified.

Debugging Cookie-Related Problems

To debug cookie-related issues, you can use browser developer tools to inspect cookies directly. Checking for any issues in cookie settings like domain, path, or expiry date is essential for diagnosing problems.

Why Run Cookie Tests on Real Devices and Browsers?

Running cookie-based tests on real devices and browsers ensures that your tests are accurate and reflect real-world scenarios. Device-specific behaviors, network conditions, and browser settings can impact how cookies are handled. Running tests in real environments helps in identifying potential issues that might not appear in local setups or emulated environments.

BrowserStack Automate offers real devices and browsers on the cloud, allowing you to test cookie handling across a variety of environments. With BrowserStack, you can run your Selenium tests on real mobile and desktop browsers, ensuring that your cookie-based automation is robust and reliable.

Conclusion

Handling cookies in Selenium is a crucial part of automating web interactions, especially when dealing with sessions and user data. Understanding how to manage cookies, preserve them across sessions, and troubleshoot common issues will make your test automation more reliable and efficient.

By implementing best practices and running tests in real environments, you can ensure that your cookie management in Selenium works seamlessly in any scenario.

Written by
Azma Banu

Related posts