
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.
Table of Contents
- What Are Cookies in Web Applications?
- Selenium Cookie Methods
- Why Handle Cookies in Selenium?
- Steps to Handle Cookies in Selenium
- Step 1: Store Authentication Cookies
- Step 2: Reuse Stored Cookies for Login
- 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:
Method | Description |
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.
Benefits:
- 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:
- Storing cookies after logging in
- 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 Code Snippet:
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 Code Snippet:
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