---Advertisement---

 Handling Cookies in Selenium WebDriver: Store, Retrieve & Reuse Login Sessions in Java Great 2025

By Manisha

Updated On:

---Advertisement---
Handling Cookies in Selenium WebDriver

Handling Cookies in Selenium WebDriver

Handling Cookies in Selenium WebDriver: In web automation testing using Selenium WebDriver, handling cookies is a crucial technique to optimize your test scripts—especially when it comes to login sessions, cart functionality, and user personalization.

This tutorial explains how to create, retrieve, delete, and reuse cookies in Selenium to save time and avoid repetitive login steps during test automation.


  1. What Are Cookies in Web Applications?
  2. Selenium Cookie Methods
  3. Why Handle Cookies in Selenium?
  4. Steps to Handle Cookies in Selenium
  5. Step 1: Store Authentication Cookies
  6. Step 2: Reuse Stored Cookies for Login
  7. Conclusion

 What Are Cookies in Web Applications?

Handling Cookies in Selenium WebDriver: Cookies are small key-value pairs stored in the browser to retain user data such as preferences, session tokens, and authentication status. They help the server recognize users across different sessions.

Example:

pgsql

Cookie: SESSIONID=xyz123; path=/; domain=.example.com


 Selenium Cookie Methods

Selenium WebDriver provides built-in methods to interact with browser cookies:

MethodDescription
driver.manage().getCookies()Returns a Set of all cookies
driver.manage().getCookieNamed(name)Returns cookie with specific name
driver.manage().addCookie(cookie)Adds a new cookie
driver.manage().deleteCookie(cookie)Deletes a specific cookie
driver.manage().deleteCookieNamed(name)Deletes cookie by name
driver.manage().deleteAllCookies()Deletes all cookies

Why Handle Cookies in Selenium?

Handling Cookies in Selenium WebDriver: When automating workflows such as:

  • Logging in
  • Adding items to cart
  • Placing an order

…you often have to perform the login action repeatedly. This results in:

  • Increased coding effort
  • Slower execution

Solution? Use cookies to persist login sessions between test cases.

  • Skip login steps by reusing authentication cookies
  • Faster test execution
  • Less boilerplate code
  • Maintain session between test cases

 Steps to Handle Cookies in Selenium

Handling Cookies in Selenium WebDriver: Handling cookies involves two major steps:

  1. Storing cookies after logging in
  2. Reusing stored cookies to bypass login

 Step 1: Store Authentication Cookies

Handling Cookies in Selenium WebDriver: This step logs into the application and stores the cookies into a file.

java

WebDriver driver = new ChromeDriver();

driver.get(“https://demo.guru99.com/test/cookie/selenium_aut.php”);

// Perform login steps here…

// Get all cookies

Set<Cookie> cookies = driver.manage().getCookies();

File file = new File(“Cookies.data”);

file.delete(); // delete old file if exists

file.createNewFile();

BufferedWriter writer = new BufferedWriter(new FileWriter(file));

for (Cookie cookie : cookies) {

    writer.write(cookie.getName() + “;” +

                 cookie.getValue() + “;” +

                 cookie.getDomain() + “;” +

                 cookie.getPath() + “;” +

                 cookie.getExpiry() + “;” +

                 cookie.isSecure());

    writer.newLine();

}

writer.close();

 Output:

A file named Cookies.data will be created with all cookie information including:

  • Name
  • Value
  • Domain
  • Path
  • Expiry

 Step 2: Reuse Stored Cookies for Login

Now you can skip the login step by loading cookies from the file into a new browser session.

java

WebDriver driver = new ChromeDriver();

driver.get(“https://demo.guru99.com/test/cookie/selenium_aut.php”);

File file = new File(“Cookies.data”);

BufferedReader reader = new BufferedReader(new FileReader(file));

String line;

while ((line = reader.readLine()) != null) {

    String[] token = line.split(“;”);

    String name = token[0];

    String value = token[1];

    String domain = token[2];

    String path = token[3];

    Date expiry = null;

    if (!token[4].equals(“null”)) {

        expiry = new Date(token[4]);

    }

    boolean isSecure = Boolean.parseBoolean(token[5]);

    Cookie cookie = new Cookie.Builder(name, value)

                        .domain(domain)

                        .path(path)

                        .expiresOn(expiry)

                        .isSecure(isSecure)

                        .build();

    driver.manage().addCookie(cookie);

}

reader.close();

// Refresh to apply cookies

driver.navigate().refresh();

 Output:

You are automatically logged in without manually entering credentials. Selenium uses the stored cookie to authenticate the session.

Tip: Use hard refresh (Ctrl + F5) if you’re redirected back to login page.


Conclusion

Using cookies in Selenium is a smart and efficient way to manage authenticated sessions, especially for large test suites that require multiple login steps.

Key Takeaways:

  • Cookies reduce redundant login actions
  • They save time and code complexity
  • Selenium provides easy-to-use cookie handling methods
  • You can persist session cookies using file storage

GitHub Integration

Testing Selenium Download

Leave a Comment

Index