Using getCookies() to get all cookies and extracting in Selenium Webdriver

Any site can have single or multiple cookies. If you know cookie name then you can get it's detail easily using getCookieNamed(). But if there are multiple cookies and you need all of them then you need to use getCookies(). Selenium webdriver get cookies will retrieve all cookies of site you are navigating in selenium webdriver test. Here we will learn how webdriver get cookies using getCookies() and extracting all cookie detail using Java Set interface and Iterate through cookie set using Iterator. selenium webdriver get cookies will help you to extract browser cookie when run selenium test.

Using getCookies() in selenium to get cookies java?
package TestPack;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

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

public class testgetCookies {

 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  
  driver.get("https://only-testing-blog.blogspot.com/2014/01/textbox.html");
  
  //Add multiple cookies with different name, value, domain, path, expiry, isSecure and isHTTPOnly.
  driver.manage().addCookie(new Cookie("Cookiename1", "1589516354637%2F1", ".only-testing-blog.blogspot.com", "/", new Date((2035-1900),05,07), false, true));
  driver.manage().addCookie(new Cookie("Cookiename2", "2589516354637%2F1", ".only-testing-blog.blogspot.com", "/", new Date((2035-1900),05,03), true, true));
  driver.manage().addCookie(new Cookie("Cookiename3", "3589516354637%2F1", ".only-testing-blog.blogspot.com", "/", new Date((2035-1900),05,04), false, false));
 
  //Get all cookie details from browser using getCookies().  
  Set<Cookie> cookies = driver.manage().getCookies();
  
  //Iterate through cookies to isolate each cookie
  Iterator value = cookies.iterator();   
  while (value.hasNext()) { 
            System.out.println(value.next()); 
        }
      }
}

Output
Cookiename1=1589516354637%2F1; expires=Sun, 07 Jun 2020 12:00:00 IST; path=/; domain=.only-testing-blog.blogspot.com;secure;
Cookiename2=2589516354637%2F1; expires=Wed, 03 Jun 2020 12:00:00 IST; path=/; domain=.only-testing-blog.blogspot.com;secure;
Cookiename3=3589516354637%2F1; expires=Thu, 04 Jun 2020 12:00:00 IST; path=/; domain=.only-testing-blog.blogspot.com;secure;
In above example you can see that We added multiple cookies with different cookies details first to see how we can get and extract all of them getCookies() and Iterator. getCookies() will get all cookies in selenium which we had set and store it in cookies set. Then iterator will extract each of them and print in console.

This way selenium get all cookies works and extract them.

No comments:

Post a Comment