Handling Cookies in Selenium WebDriver


This post is dedicated to handling of cookies using Selenium webdriver. We will be studying about cookies, the need of automating cookie handling scenarios and different methods provided by Selenium to add, get and delete cookies.

What are Cookies?

Cookies are files stored in local computers containing information submitted by the websites visited by a user. The information is stored in key-value pairs and allows a particular website to customize its content as per the user.

Handling cookies in Selenium

Need of Handling Cookies in Automation

During automation we might need to handle cookies for following reasons-

  1. There could be scenarios specific to cookies which needs to be automated and requires validating enteries in cookie files.
  2. If we could create and load cookie files during automation, we can skip some scenarios like login to application for each test case as the same gets handled by cookies. E.g. in some application like GMail, we only need to login once, after that the login information gets stored in cookies and loaded each time we open gmail link. This saves the overall test execution time.

Get Cookies in Selenium

We can get Cookies in Selenium WebDriver in two ways-

  1. getCookieNamed(String cookieName) - To get a particular Cookie by name
  2. getCookies() - To get all the Cookies in the current domain.
//To fetch a Cookie by name
System.out.println(driver.manage().getCookieNamed(cookieName).getValue());

//To return all the cookies of the current domain
Set<Cookie> cookiesForCurrentURL = driver.manage().getCookies();
for (Cookie cookie : cookiesForCurrentURL) {
    System.out.println(" Cookie Name - " + cookie.getName() 
			+ " Cookie Value - "  + cookie.getValue()));
}

Add Cookies in Selenium

addCookie(Cookie cookie) - To add a particular Cookie in Selenium WebDriver.

Cookie cookie = new Cookie("cookieName", "cookieValue");
driver.manage().addCookie(cookie);

Delete Cookies in Selenium

Delete Cookies in Selenium WebDriver can be done in three ways-

  1. deleteCookieNamed(String cookieName) - To delete a particular Cookie by name.
  2. deleteCookie(Cookie cookie) - To delete a particular Cookie.
  3. deleteAllCookies() - To delete all the Cookies.
//Delete a particular Cookie by name
driver.manage().deleteCookieNamed(cookieName);

//Delete a particular Cookie
driver.manage().deleteCookie(cookie);

//Delete all the Cookies
driver.manage().deleteAllCookies();