Home Guide How to Handle Cookies in Selenium?

How to Handle Cookies in Selenium?

By Neha Vaidya, Community Contributor -

When a website loads, it is common to come across a pop-up that asks the users to provide permission to the site for running cooking. Basically, a cookie is a piece of information that consists of a name, value, expiry, path, etc. It helps a user retain the search history, login, and other relevant details.

This article will give insight into handling cookies in Selenium while automating tests on web pages and web apps.

Introduction to Selenium Cookies

A cookie is a small piece of data that is sent from a website and stored on the user’s computer. Cookies are also used to recognize the user if they return to a website, and load the previously stored information. Mostly, cookies store the user’s identity and track the user’s journey through the pages of the website. WebDriver API provides a way to interact with cookies with built-in methods.
Now, let’s have a 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

Why is Cookie Handling necessary?

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 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. That 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 as authenticated and directly takes the tester to the requested URL. This is why cookie handling is necessary.

Working with Cookies using Selenium – Example

The code 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 having to enter login credentials.

How to clear browser cache using Selenium?

Method #1

Clearing browser cookies before starting your test is important. If the tester is using Selenium WebDriver for test automation, they can use the method below to clear all cookies. 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 on the button and then click on Inspect to open Chrome Developer Tools.
  4. Now locate the element using XPath or Chropath. 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. By following what this article details, testers can handle Selenium cookies easily and accurately test some of the most common user scenarios to ensure a good user experience.

BrowserStack Logo Run Selenium Tests on 2000+ Browsers & Devices Get Started Free