App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to handle Cookies in Selenium WebDriver

How to handle Cookies in Selenium WebDriver

By Neha Vaidya, Community Contributor -

When a website loads, it is common to see a pop-up asking the users to provide permission to the site to run cookies. A cookie is a piece of information that consists of a name, value, expiry, path, etc. It helps users retain the search history, login, and other relevant details.

This article will shed insights on cookies handling in Selenium WebDriver with code examples and how to clear the browser cache in Selenium with two easy methods.

Introduction to Selenium WebDriver Cookies

A cookie is a small piece of data sent from a website and stored on the user’s computer. Cookies also recognize users returning to a website and loading the previously stored information. Mainly, cookies store the user’s identity and track the user’s journey through the website’s pages. WebDriver API provides a way to interact with cookies with built-in methods.
Now, let’s look at the various Selenium commands for cookies.

Selenium Commands for Cookies

The commands below are used to get, add, and delete all cookies present in a browser:

  • Get Cookie: Gets the cookies for the current domain.
driver.manage().getCookies(); // Returns the List of all Cookies
driver.manage().getCookieNamed(arg0); //Returns the specific cookie according to name
  • Add Cookie: Adds a specific cookie into cookies. If the cookie’s domain name is blank, it is assumed that the cookie is meant for the domain of the current document.
driver.manage().addCookie(arg0); //Creates and adds the cookie
  • Delete Cookie: Deletes the cookies for the current domain.
driver.manage().deleteCookie(arg0); // Deletes the specific cookie
driver.manage().deleteCookieNamed(arg0); // Deletes the specific cookie according to the Name
driver.manage().deleteAllCookies(); // Deletes all the cookies

Importance of Cookie Handling in Selenium Automation WebDriver

When testing a web application using Selenium Webdriver, testers can create, update or delete a cookie.

  • For example, when automating an online food delivery application, the tester needs to automate various user scenarios like placing an order, viewing a cart, paying, receiving the order confirmation, etc.
  • If cookies are not stored, the user needs to log in every time before executing the test scenarios listed above.
  • This increases coding effort and execution time.

The solution here is to store cookies in a file. Then, the values of each cookie can be retrieved from this file and added to the current browser session. Therefore, testers skip the login steps in every test case because the driver session has this information. The application server now treats the browser session authenticated and directly takes the tester to the requested URL. This is why cookie handling in Selenium Webdriver is necessary.

Handling Cookies in Selenium WebDriver (Example)

The following code snippet demonstrates how to store cookies in a file system and retrieve the necessary information with the help of Selenium WebDriver.

import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileWriter;
import java.util.Set;
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Cookie;

public class cookieRead{ 

public static void main(String[] args){
WebDriver driver; 
System.setProperty("webdriver.chrome.driver","Chrome_driver_path"); 
driver=new ChromeDriver(); 
driver.get("https://www.facebook.com");
//Enter Email id and Password if you are already Registered user 
driver.findElement(By.name("username")).sendKeys("your_username"); 
driver.findElement(By.name("password")).sendKeys("your_password"); 
driver.findElement(By.name("submit")).click(); 
// Create a file to store Login Information 
File file = new File("Cookiefile.data"); 
try{ 
// Delete old file if already exists
file.delete(); 
file.createNewFile(); 
FileWriter file = new FileWriter(file); 
BufferedWriter Bwritecookie = new BufferedWriter(file); //Getting the cookie information 
for(Cookie ck : driver.manage().getCookies()) { 
Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure())); 
Bwritecookie.newLine(); 
} 
Bwritecookie.close(); 
file.close(); 
}
catch(Exception ex) 
{ 
ex.printStackTrace(); 
} 
} 
}
  • When the code is executed, WebDriver will store the cookie information using FileWriter Class to write streams of characters and BufferedWriter to write the text into a file named “Cookiefile.data“.
  • The file stores cookie information – “Name, Value, Domain, Path”.
  • The tester can retrieve this information and log in without entering login credentials.

Also Read: Login Automation using Selenium Webdriver

How to clear the Browser Cache using Selenium WebDriver?

Method 1

  1. Clearing browser cookies before starting your test are essential.
  2. If the tester uses Selenium WebDriver for test automation, they can use the method below to clear all cookies.
  3. Create a void method below and then call the method before navigating to the application URL.
public void ClearBrowserCache()
{
webDriver.Manage().Cookies.DeleteAllCookies(); //delete all cookies
Thread.Sleep(7000); //wait 7 seconds to clear cookies.
}

Method 2

  1. Navigate to the Chrome settings page with Selenium by executing the driver.get(‘chrome://settings/clearBrowserData’) .
  2. Click on the Clear Data button to clear the cache.
  3. Right-click the button and then click on Inspect to open Chrome Developer Tools.
  4. Now locate the element using XPath or Chropath.
  5. Use it in the Selenium script and apply wait commands to wait till the cache is cleared.

Handling cookies in Selenium is simple if one knows the right commands. Following this article’s details, testers can easily handle Selenium cookies and accurately test some of the most common user scenarios to ensure a good user experience.

Note – Selenium tests must be run on Real browsers and devices for accurate results.

  • Start running tests on 3000+ real browsers and devices on BrowserStack’s Real Device Cloud.
  • Run parallel tests on a Cloud Selenium Grid to get faster and more accurate results.
  • Detect bugs before users do by testing software in real user conditions.

Sign up for Selenium Testing

While Selenium 4 has just been released, Selenium Webdriver will be completely W3C standardized. Browsers such as Chrome, Safari, Firefox, IE, and Edge will also follow W3C standardization, bringing stability around Selenium Commands.

In the following webinar, David Burns, core contributor to Selenium, talks about how this would impact your tests and new features you can start using immediately.

How to handle Cookies in Selenium WebDriver

Tags
Selenium Selenium Webdriver

Featured Articles

5 Selenium tricks to make your life easier

7 practices for efficient Selenium Web Browser Automation

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.