A HTTP cookie is comprised of information about the user and their preferences. It stores information using a key-value pair. It is a small piece of data sent from Web Application and stored in Web Browser, while the user is browsing that website.

Click here to learn about cookie testing.

In this tutorial, we will learn -

Selenium Query Commands for cookies

In Selenium Webdriver, we can query and interact with cookies with below built-in method:

driver.manage().getCookies();   // Return The List of all Cookies
driver.manage().getCookieNamed(arg0);  //Return specific cookie according to name
driver.manage().addCookie(arg0);   //Create and add the cookie

driver.manage().deleteCookie(arg0);  // Delete specific cookie

driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according Name

driver.manage().deleteAllCookies();  // Delete all cookies

Why Handle Cookies in Selenium?

Each cookie is associated with a name, value, domain, path, expiry, and the status of whether it is secure or not. In order to validate a client, a server parses all of these values in a cookie.

When Testing a web application using selenium web driver, you may need to create, update or delete a cookie.

For example, when automating Online Shopping Application, you many need to automate test scenarios like place order, View Cart, Payment Information, order confirmation, etc.

If cookies are not stored, you will need to perform login action every time before you execute above listed test scenarios. This will increase your coding effort and execution time.

The solution is to store cookies in a File. Later, retrieve the values of cookie from this file and add to it your current browser session. As a result, you can skip the login steps in every test case because your driver session has this information in it.

The application server now treats your browser session as authenticated and directly takes you to your requested URL.

Demo: Cookie handling in Selenium.

We will use http://demo.avactis.com for our demo purpose.

This will be a 2 step process.

Step 1) Login into application and store the authentication cookie generated.

Step 2) Used the stored cookie, to again login into application without using userid and password.

Step 1) Storing cookie information.

package com.avactis.test.handleCookie

import java.io.BufferedWriter;		
import java.io.File;		
import java.io.FileWriter;		
import java.util.concurrent.TimeUnit;		

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

public class HandlyingCookies		
    Static WebDriver driver;	

    public static void main(String[] args)					
    		driver=new ChromeDriver();        

        // Input Emial id and Password If you are already Register		
        driver.findElement(By.xpath(".//*[@id='account_sign_in_form_passwd_id']")).sendKeys("<< Password>>");							
        // create file named Cookies to store Login Information		
        File file = new File("Cookies.data");							
            // Delete old file if exists
            FileWriter fileWrite = newFileWriter(file);							
            BufferedWriter Bwrite = newBufferedWriter(fileWrite);							
            // loop for getting the cookie information 		
            for(Cookie ck : driver.manage().getCookies())							
        }catch(Exception ex)					

Code Explanation:

  • Create WebDriver instance
  • We visit the website using the driver.get("http://demo.avactis.com/4.7.9/")
  • Login into the Application
  • Read the cookie information using


  • Store the cookie information using FileWriter Class to write streams of characters and BufferedWriter to write the text into a file to create into a file Cookies.data
  • "Cookies.data" file stores all cookies information along with "Name, Value, Domain, Path". We can retrieve this information and login into the application without entering the login credentials.
  • Once you run above code the Cookie.data file is created into the project folder structure as shown in below screen,

    Cookie Handling in Selenium WebDriver

  • Open the Cookie.data file, you can see login credential of online shopping application(demo.avactis.com) is saved in the format of Cookie, see below-highlighted screen.

Cookie Handling in Selenium WebDriver

Step 2) Using stored cookie to login into the application.

Now, we will access the cookie generated in step 1 and use the cookie generated to authenticate our session in the application

package com.avactis.test.handleCookie

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 LoadCookiesData		
    staticWebDriver driver;					
    public static void main(String[] args)					
    {        System.setProperty("webdriver.chrome.driver","/OnlineShopping/InputData/chromedriver.exe");					
    driver=new ChromeDriver();					
        File file = new File("Cookies.data");							
        FileReader fileReader = new FileReader(file);							
        BufferedReader Buffreader = new BufferedReader(fileReader);							
        String strline;			
        String Tokenizertoken = newStringTokenizer(strline,";");									
        String name = token.nextToken();					
        String value = token.nextToken();					
        String domain = token.nextToken();					
        String path = token.nextToken();					
        Date expiry = null;					
        String val;			
        	expiry = new Date(val);					
        Boolean isSecure = new Boolean(token.nextToken()).								
        Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);																	
        driver.manage().addCookie(ck); // This will add the stored cookie to your current session					
        }catch(Exception ex){					


Thus, you can avoid entering the username and password on the server validating them again and again for each test with the help of Selenium Webdriver, and thereby saves a lot of time.

This article is contributed by Mangesh Waghmare