How to Extract Cookies in a Page


This post helps you,How to extract Cookies in a page.We can Add/Delete Cookies by using few methods.

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 Cookies {
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.xyz.com”);
}

@Test
public void extrctCookie(){
//Get and extract all cookies of google domain and print cookie parameters.
Set 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()));
}
}
}

Advertisements

5 thoughts on “How to Extract Cookies in a Page

  1. armatearjun June 15, 2015 / 2:27 pm

    Please change “Set totalCookies = driver.manage().getCookies();” to “Set totalCookies = driver.manage().getCookies();” since getCookies() method will return a set of cookies… Thanks

    Like

  2. armatearjun June 15, 2015 / 2:27 pm

    sorry to this… Set” totalCookies = driver.manage().getCookies();

    Like

  3. armatearjun June 15, 2015 / 2:28 pm

    sorry i am not able to comment with in tags cookie

    Like

  4. Shanky Kalra December 13, 2016 / 4:29 pm

    Set cookies = driver.manage().getCookies();

    Iterator itr = cookies.iterator();
    while (itr.hasNext()){
    Cookie c = itr.next();
    System.out.println(“—–Cookies Detail—–“);
    System.out.println(“Cookie Name: ” + c.getName() + “\n\tCookie Domain: ” + c.getDomain() + “\n\tCookie Value: ” + c.getValue() + “\n\tPath: ” + c.getPath()+ “\n\tExpiry Date: ” + c.getExpiry()+ “\n\tSecure: ” + c.isSecure());
    }

    Update the Code with above code snippet.

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s