How To Extract Domain Cookie In Selenium WebDriver Test

You must know what Is cookies before learning how to extract or manage cookies In selenium WebDriver. Cookies are small text files created by website when you access It to remember some data for you to use It In future. Cookies contains domain name for which It Is created, Cookie name
and Its value. It also contains validity duration of cookie. As per testing point of view, sometimes you need to extract cookies. Bellow given example will show you how to extract and print cookies In selenium WebDriver test.

WebDriver has cookie class which contains many different functions using which we can get the cookies and Its different parameters. Few of the functions I have used In bellow given example like

  • getDomain() - To get domain name of cookie.
  • getName() - To get name of cookie.
  • getValue() - To get value of cookie.
  • getExpiry() - To get expiry date of cookie.
Run below given example In your eclipse IDE. It will retrieve above details of cookie for google domain. 

package Testing_Pack;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class extractCookies {
 WebDriver driver;
 
 @BeforeTest
 public void setup() throws Exception {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://www.google.com");
 }
 
 @Test
 public void extrctCookie(){  
  //Get and extract all cookies of google domain and print cookie parameters. 
  Set<Cookie> totalCookies = driver.manage().getCookies();
  System.out.println("Total Number Of cookies : " +totalCookies.size());
  
  for (Cookie currentCookie : totalCookies) {
      System.out.println(String.format("%s -> %s -> %s -> %s", "Domain Name : "+currentCookie.getDomain(), "Cookie Name : "+currentCookie.getName(), "Cookie Value : "+currentCookie.getValue(), "Cookie Expiry : "+currentCookie.getExpiry()));
  }  
 }
}

At the end of execution, You will get cookie detail In console. You can change domain name In above example to get cookie detail In selenium WebDriver test. Next post will show you how to add new cookie.

2 comments:

  1. Thanks again for this tutorial

    ReplyDelete
  2. Hi,
    i am getting this error "Cannot find class in classpath: newmoduledesign.cookies" while running the code.

    ReplyDelete