Get Cookie by Name
To get a cookie by name using Selenium for Java, call manage().getCookieNamed()
on the WebDriver object and pass the name of the cookie as argument to the getCookieNamed()
method.
The following is a simple code snippet to get the cookie by name “GeoIP”.
</>
Copy
driver.manage().getCookieNamed("GeoIP")
where driver
is a WebDriver object.
This expression returns a Cookie object.
Example
In the following program, we write Selenium Java code to visit Wikipedia Home Page, and get the Cookie named GeoIP.
Java Program
</>
Copy
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class MyAppTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
WebDriver driver = new ChromeDriver();
try {
driver.get("https://en.wikipedia.org/wiki/Main_Page");
//get cookie by name
Cookie cookie = driver.manage().getCookieNamed("GeoIP");
System.out.println(cookie);
} finally {
driver.quit();
}
}
}
Output
GeoIP=IN:TG:Hyderabad:19.00:99.99:v4; path=/; domain=.wikipedia.org;secure;
Screenshot