9121822375 sdetforum@gmail.com

Welcome, Today is awesome and I want to share a program on Cookies 🙂

First of all, Cookie is small information which is set by the server on the client machine. The main purpose of cookies is to control/track user behavior on the website.

As soon as the server receives the request from the client (ex: chrome, firefox, windows, Linux…etc), the server will process and send back the response along with some trackers which are going to be on the client machine, these trackers are going to expire or sometimes they will stay until you clear your browser history along with cookies.

Selenium provides a class and different methods do deal with Cookies, you can find more details from here.

Program to Print all Cookies from Any website

package testngexamples;

import java.util.Set;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class PrintAllCookiesExp {
	WebDriver driver;
	public void init() throws InterruptedException
		// to launch browser and launch AUT
		System.setProperty("webdriver.chrome.driver", "D:\\browser-drivers\\chromedriver.exe");
		 driver = new ChromeDriver();
	public void printAllCookies() throws InterruptedException
		// print all cookies
		Set<Cookie> cookie1 = driver.manage().getCookies();
		// print all cookies names and values using for each loop
		for(Cookie cookie2     :   cookie1  )
			// print cookie name
			String cookie_name = cookie2.getName();
			System.out.println("Cookie Name is:" +cookie_name);
			// print cookie value
			String cookie_value  = cookie2.getValue();
			System.out.println("Cookie Value is:" +cookie_value);
	public void tearDown()
Points to Note
  • Cookie is small information which is set on Client machine by server to track user behaviour.
  • Cookie is a class in Selenium , which deals with variety of functionalities related to cookies.
  • Selenium used Set interface to get all cookies, reason is cookies should not be duplicate, so Set interface won’t allow duplicates.
  • For-Each loop is best fit when you want to deal with collection of data.