Site icon TestingDocs.com

Selenium : Working with Cookies

Overview

In this post, we will discuss working with cookies with selenium. Cookies are small text files stored on your computer, that contain information sites that is needed to remember of our visit example like our preferences that the sites will persist while browsing the web pages. Cookies are used by the browser at the time you access the website. A website can only set cookies valid on it’s domain and sub-domains, not on domains that do not belong to them. Furthermore, some cookies can also have an expiry date set.

Working with cookies

A Cookie object must have at least two attributes, viz. name and value.

The Cookie object offers several constructors to build our cookie object.

Example :

Cookie samplecookie = new Cookie(“sampleCookie”, “sampleValue”);

Environment used for sample test in this post:

OS : Windows 10 operating system.

Browser: Microsoft Edge Browser.

Get cookies

After opening a web page we can use the below method to get cookies:

Set<Cookie> cookies = driver.manage().getCookies();

Sample code:

@Test
public void getCookieTest()
{
System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe");
driver=new EdgeDriver();
driver.get("https://www.bing.com");
Set<Cookie> cookies = driver.manage().getCookies();
  
for(Cookie cookie : cookies){
System.out.println(cookie);
}
  
}

 

We can run the test and check the cookies.

Get a certain cookie: When you know the name of the cookie we can use:

driver.manage().getCookieNamed(“samplecookieName”);

Adding a cookie

driver.manage().addCookie(sampleCookie);

@Test
public void addCookieTest()
{
System.setProperty("webdriver.edge.driver", "MicrosoftWebDriver.exe");	
driver=new EdgeDriver();
driver.get("https://www.bing.com");
Cookie samplecookie= new Cookie("SampleCookie", 
"Cookie Content");
driver.manage().addCookie(samplecookie);
Set<Cookie> cookies = driver.manage().getCookies();
    
for(Cookie cookie : cookies)
 {
 if(cookie.getValue().contains("music"))
 System.out.println(cookie);
 }
}

 

Run the program and see the cookie that we have set :

INFO: Detected dialect: OSS
SampleCookie=Cookie Content; path=/; domain=www.bing.com

Deleting cookies

driver.manage().deleteAllCookies();

Deleting  a particular cookie, whose name we  know

driver.manage().deleteCookieNamed(“sampleCookieName”);

 

Selenium WebDriver Tutorials on this website can be found at:

https://www.testingdocs.com/selenium-webdriver-tutorial

For more details on the Selenium, visit the official website at:

https://www.selenium.dev/

Exit mobile version