Software Testing Class

How to handle Cookies in Selenium WebDriver

In this tutorial, we are going to discuss the handling of cookies using Selenium WebDriver. Before we start using Selenium Webdriver to store information in the cookie and retrieve from it, let’s first explore some more about HTTP Cookie.

 

Introduction To Cookie

Perhaps you have done online shopping and notices the shopping cart that is often present on the top right corner of the website. When you do shopping on such websites and add items to the shopping cart, the information gets stored in the browser cookie. Therefore, if you left your shopping cart with added items to it and log off and re-login on the same browser and website then you will find those items already added to the shopping cart. This magic is possible as a result of HTTP cookie that is present in the web browser. Let’s discuss further, what are HTTP Cookie and how it works?

Handle Cookies In Selenium WebDriver

You may want to read about Cookie Testing here.

 

What Is An HTTP Cookie And How It Works?

HTTP Cookie is also called as a web cookie, a browser cookie or an Internet cookie. It is nothing but a text file present in the web browser of the client machine or PC that stores a small piece of information received from a website as a key-value pair when the user does the web browsing. When a user loads that website again, the browser sends back the stored cookie to the server that notifies it about the user’s past activities. HTTP Cookies store not only the user’s browsing history but also the shopping cart information for an online store, login user ids and passwords and other related information.

 

Selenium WebDriver Query Commands For Cookies

Using Selenium WebDriver API, we can query and interact with browser cookies with the help of following WebDriver’s built-in methods.

Get Cookies: This statement is used to return the list of all Cookies stored in web browser.

manage().getCookies();


Get Cookies by name:
 This statement is used to return the specific cookie according to its name.

manage().getCookieNamed(arg0);

 

Add Cookies: This statement is used to create and add the cookie.

manage().addCookie(arg0)

 

Delete Cookies: This statement is used to delete a specific cookie.

manage().deleteCookie(arg0);

 

Delete Cookies by name: This statement is used to delete a cookie according to its name.

manage().deleteCookieNamed(arg0);

 

Delete All Cookies: This statement is used to delete all cookies.

manage().deleteAllCookies();

 

Handling Cookies In Selenium

A cookie has the following fields, let’s understand it with the following example.

HTTP/1.0 200 OK

Set-Cookie: NAME=SELENIUM; Expires=Thu, 19 May 2020 10:23:07 GMT; Path=/softwaretestingclass; Domain=abc.com; Secure; HttpOnly

Given below is the description of all fields.

We need to create, update or delete a cookie to test a web application using Selenium WebDriver. Therefore, if we are automating any Online Shopping website then we need to automate test scenarios such as add item to shopping cart, view cart, confirm the purchase, payment, etc. Without storing details into cookies we may need to perform login again and again to run these scenarios that will increase our coding effort and execution time. Therefore, we store a cookie in a file and later retrieve these values and it to our current browser session. This saves both the coding effort and execution time.

Following is the demonstration of Cookie handling using Selenium WebDriver in two steps.


package seleniumpackage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class StoringCookie
{
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", ".//chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://easyweb.td.com/waw/idp/login.htm?execution=e1s1");
driver.findElement(By.name("login:AccessCard")).sendKeys("0000111122223333");
driver.findElement(By.name("login:Webpassword")).sendKeys("testingclass");
driver.findElement(By.name("rememberMeCBox")).click();
driver.findElement(By.id("login")).submit();
// create file named Cookie to store username Information
File file = new File("Cookie.data");
try { // Delete if any old file exists
file.delete();
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferwrite = new BufferedWriter(fileWriter);
for(Cookie cook : driver.manage().getCookies()){
String writeup = cook.getName()+";"+cook.getValue()+";"+cook.getDomain()+";"+cook.getPath()+""
+ ";"+cook.getExpiry()+";"+cook.isSecure();
bufferwrite.write(writeup);
System.out.println(writeup);
bufferwrite.newLine();
}
bufferwrite.flush();bufferwrite.close();fileWriter.close();
}catch(Exception exp){
exp.printStackTrace();
}
}
}

Output

When we run the above test script, we will procure the following output. In the console, it is displaying the encrypted cookie details stored in a web browser.

Following is the screenshot of the website that gets loaded after executing the above Selenium WebDriver script.


package seleniumpackage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RetrievingCookie
{
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", ".//chromedriver.exe");
driver=new ChromeDriver();
try{
File file = new File("Cookie.data");
FileReader fileReader = new FileReader(file);
BufferedReader Buffreader = new BufferedReader(fileReader);
String strline;
while((strline=Buffreader.readLine())!=null){
StringTokenizer token = new StringTokenizer(strline,";");
while(token.hasMoreTokens()){
String name = token.nextToken();String value = token.nextToken();
String domain = token.nextToken();String path = token.nextToken();
Date expiry = null;
String val;
if(!(val=token.nextToken()).equals("null")){
expiry = new Date(val);
}
Boolean isSecure = new Boolean(token.nextToken()).booleanValue();
Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck); // This will add the stored cookie to our current session
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("https://easyweb.td.com/waw/idp/login.htm?execution=e1s1");
}
}

 

⇓ Download Selenium Code ⇓

How To Handle Cookies In Selenium WebDriver

Over to you:

In this tutorial, we have discussed HTTP Cookie, its properties and various methods present in Selenium WebDriver to handle web browser Cookies. We demonstrated an example where we were storing cookie into a file and later retrieving the details from this file and loading on the same page. This WebDriver API to handle Cookie is very useful to test such applications where login information could be stored in the Cookie and we may skip the effort of login, again and again, using username and password instead we can retrieve this information in Cookie file and save the coding effort as well as executing test script time.

Exit mobile version