How To Handle Cookies in Selenium WebDriver
Published: 2022-02-11 10:45:37

Most of us use online platforms for doing things like online shopping, bill payments, ticket booking, and more. These online platforms (or websites) use cookies to identify whenever there is a new visit. On a lighter note, these are not cookies that you would normally see on your dessert menu 🙂 These are computer cookies (or HTTP cookies or web cookies).

In simple terms, a cookie is a packet of data received by your machine and sent back to the server without being altered or changed. For example, when you visit any website, cookies are sent to your machine by the website. Since these cookies contain information, it helps the website keep track of your visits or activity (without indulging in your privacy zone).


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29d7n6tabwawiz6r6bz6.gif)

Website owners (e.g., online shopping portals) use cookies to keep a tab on your shopping cart while browsing the site. Without the presence of cookies, your shopping cart might become empty (or the item count would reset to zero) each time you open up a new link on the site.

Selenium cookies can be extensively used for test automation projects for performing cookie-related operations during the process of [Selenium automation testing](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=feb11_sb&utm_term=sb&utm_content=blog). To realize this requirement, Selenium WebDriver API provides built-in methods for interacting with the cookies.

By the end of this blog, you would be better positioned to work with Selenium cookies API. We also cover common operations like how to get cookies in Selenium WebDriver, clearing session cookies using Selenium, and more.

So, let’s get started biting the cookies 🙂

## Introduction to Cookies

Cookies are usually used to recognize the identity of a user on a website. In simple terms, a cookie is a portion of data that has been sent from a web application and stored in a browser. Whenever a user browses a website, the information about the user and their favorites is stored as a cookie in the form of key-value pairs.

When the user visits the website again, the information which was stored would be used for identification.

Below is an example of the LambdaTest website that uses cookies for recognizing the user. In the below screenshot, you can see a small popup that shows the usage of cookies.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/944vwog2sc85h2qnjs69.png)

- Name – This field contains the cookie’s name.
- Value – This field contains the cookie’s value.
- Domain – This field contains the hosts that are allowed to receive the cookie.
- Path – This field contains the URL required in the requested URL to send the Cookie header.
- Expires / Max-Age – This field contains the expiration date or the maximum age of the cookie.
- Size – This field contains the size of the cookie.
- HttpOnly – This field indicates whether the cookie has to be used only over HTTP or not.
- Secure – This field indicates that the cookie can only be sent to the server over a secure HTTPS connection (set as true).
- SameSite – This field contains the values (strict or lax) if the cookie is using the experimental SameSite attribute.
- Priority – This field Contains low, medium (default), or high values if the depreciated cookie Priority attribute is enabled.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9imapbn1zy5s12i42wv.png)

Here are the major functions of website cookies:

1. Tracking the browsing activity of the user
2. Remembering the login details of the user
3. Tracking the visitor count in a website further helps the website owners identify their unique visitors every day.

***If you are looking for a [random character generator](https://www.lambdatest.com/free-online-tools/random-character-generator?utm_source=devto&utm_medium=organic&utm_campaign=jul14_sb&utm_term=sb&utm_content=blog). Here the is best [random character generator](https://www.lambdatest.com/free-online-tools/random-character-generator?utm_source=devto&utm_medium=organic&utm_campaign=jul14_sb&utm_term=sb&utm_content=blog) you can find.***

## Why handle cookies in Selenium Automation WebDriver

This section unearths the major reasons for using Selenium cookies API in a test automation script. The important aspect of storing cookies and handling them in our automation script is to reduce the time taken for implementation and execution.

Take the case where we have multiple test cases, and each of them has a prerequisite to log into the website. In such scenarios, we can store the cookies, which can then be used for login purposes. This, in turn, helps in reducing the execution time.

### Introduction to Selenium Cookies API

Selenium WebDriver provides multiple commands for handling the cookies in a website. These Selenium cookies APIs provide you the required mechanism for interacting and querying the cookies. In Selenium Java, these methods are a part of the org.openqa.selenium.Cookie package.

Here are the various methods to handle cookies in Selenium that can be accessed using driver.manage() method:



|               Method               |                                 Purpose                               |
|------------------------------------|-----------------------------------------------------------------------|
| getCookies()                       | It returns the list of all the cookies                                |
| getCookieNamed(“Name of Cookie”)   | It returns the cookie that matches the name specified as the argument |
| addCookie(“Cookie”)                | It creates and adds a new cookie                                      |
| deleteCookie(“Cookie”)             | It deletes a particular cookie                                        |
| deleteCookieName(“Name of Cookie”) | It deletes the cookie that matches the name specified as the argument |
| deleteAllCookies                   | It deletes all the cookies                                            |

### Selenium Cookies API in Action

Now that we have covered the basic aspects of handling cookies in Selenium WebDriver let’s get our hands dirty with some implementation. For demonstrating handling cookies in Selenium, we first use the corresponding Selenium APIs on a local Selenium Grid. If you want to quickly brush up on your Selenium skills, check out our detailed [Selenium WebDriver](https://www.lambdatest.com/blog/selenium-webdriver-tutorial-with-examples/?utm_source=devto&utm_medium=organic&utm_campaign=feb11_sb&utm_term=sb&utm_content=blog) tutorial.

Let us use the [LambdaTest home page](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=feb11_sb&utm_term=sb&utm_content=blog) in our script to understand the commands used for handling cookies using Selenium WebDriver.

**1. How to Get Cookies in Selenium WebDriver**

As mentioned earlier, if you want to get all the stored cookies, you can use the below Selenium WebDriver command.


```
driver.manage().getCookies()
```


This will retrieve details of all the stored cookies. Below is a simple script to get cookies in Selenium WebDriver:

```
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class HandleCookies {
    
    public static void main(String args[]) {
 System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
        WebDriver driver = new ChromeDriver();
        String url ="https://www.lambdatest.com/";
        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        Set<Cookie> cookiesList =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesList) {
            System.out.println(getcookies);
        }
        driver.close();
    }
}
```

The cookie information can be stored in a file that can be used for logging into the website without the credentials.

To get information about a specific cookie, use the below command:

```
driver.manage().getCookieNamed(arg0);
```
Below is a simple script for getting information about a specific cookie:

```
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class HandleCookies {
    
    public static void main(String args[]) {
        System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
        WebDriver driver = new ChromeDriver();
        String url ="https://www.lambdatest.com/";
        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        
        Cookie cookieValue = driver.manage().getCookieNamed("JSESSIONID");
        System.out.println(cookieValue.getValue());
        
        driver.close();
    }
}
```

The implementation is self-explanatory; hence, we are not doing a code walkthrough of the same.

**2. How to Add a new Cookie in Selenium WebDriver**

To add a new cookie, you can use the below command

```
driver.manage().addCookie(cookieName); //specify the name of the cookie to be added
```

Before adding a cookie, we have to create it and add the values. Post that, we should pass the name of the newly created cookie.

Here is a simple script that demonstrates Selenium cookies API for adding a new cookie.

```
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class HandleCookies {
    
    public static void main(String args[]) {
        System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
        WebDriver driver = new ChromeDriver();
        String url ="https://www.lambdatest.com/";
        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        
        //For creating a new cookie we should pass the name of the cookie and its value
        Cookie cname = new Cookie("myCookie", "12345678999");
        driver.manage().addCookie(cname);
 
//retrieve the cookies to view the newly added cookie
        Set<Cookie> cookiesList =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesList) {
            System.out.println(getcookies );
        }
        driver.close();
    }
}
```

Once you run the test script, you would be able to see the newly added cookie in the output console:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7i2nt1r87k3ut1o1rsu.png)

**3. How to Delete a Cookie in Selenium WebDriver**

With the help of the Selenium WebDriver commands, you can delete a specific cookie or delete all the cookies.

This command is used for deleting a specific cookie:

```
driver.manage().deleteCookie(arg0); // Deletes the specific cookie
```

This command is used for deleting a specific cookie that is matched using its name:

```
driver.manage().deleteCookieNamed(arg0); // Deletes the specific cookie by its name
```
This command is used for deleting all the cookies:

```
driver.manage().deleteAllCookies(); // Deletes all the cookies
```

Here is the same script that demonstrates how to delete a specific cookie:

```
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class HandleCookies {
    
    public static void main(String args[]) {
        System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
        WebDriver driver = new ChromeDriver();
        String url ="https://www.lambdatest.com/";
        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        
        //For creating a new cookie we should pass the name of the cookie and its value
        Cookie cname = new Cookie("myCookie", "12345678999");
        driver.manage().addCookie(cname);
 
        Set<Cookie> cookiesList =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesList) {
            System.out.println(getcookies );
        }
        
        //delete the newly created cookie
        driver.manage().deleteCookie(cname);
        Set<Cookie> cookiesListNew =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesListNew) {
            System.out.println(getcookies );
        }
        driver.close();
    }
}
```

The below script demonstrates how to use Selenium cookies API for deleting all the cookies:

```
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class HandleCookies {
  
    public static void main(String args[]) {
        System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
        WebDriver driver = new ChromeDriver();
        String url ="https://www.lambdatest.com/";
        driver.get(url);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        
        
        driver.manage().deleteAllCookies();
        Set<Cookie> cookiesListNew =  driver.manage().getCookies();
        cookiesListNew.size();
        System.out.println("The size is "+cookiesListNew);
 
        driver.close();
    }
}
```

***Did you know? [Random Color Generator](https://www.lambdatest.com/free-online-tools/random-color-generator?utm_source=devto&utm_medium=organic&utm_campaign=jul14_sb&utm_term=sb&utm_content=blog) is an online tool that generates a list of random colors or a single random color in different color code formats: HEX, RGB(A), and HSL.***

## How to use Selenium Cookies API on Cloud Selenium Grid

Rather than running Selenium tests on a local Selenium Grid, it is recommended to execute the same on a cloud-based Selenium Grid like LambdaTest. There are numerous benefits of website testing on cloud since it helps achieve much-needed scalability, reliability, and performance.

LambdaTest provides an online cloud platform to run all your Selenium tests with ease. In addition, it is easy to port the code that uses the local Selenium Grid to LambdaTest’s cloud-based Selenium Grid. Thus, you can make the most out of parallel testing in Selenium by moving the Selenium test automation to a cloud-based Grid.

Once you have created an account on LambdaTest, note the username & access key available in the profile section of LambdaTest. The combination of username & access key is used for accessing the Remote Selenium Grid of LambdaTest. The capabilities are generated using the [LambdaTest capabilities generator](https://www.lambdatest.com/capabilities-generator/?utm_source=devto&utm_medium=organic&utm_campaign=feb11_sb&utm_term=sb&utm_content=blog).

Shown below is the demonstration of Selenium cookies API with the execution being performed on the LambdaTest Selenium Grid:

```
package Pages;
 
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class HandleCookies
{
    String username = "Your_username"; //Enter your username 
    String accesskey = "Your_accessKey"; //Enter your accesskey
        
    static RemoteWebDriver driver = null;
    String gridURL = "@hub.lambdatest.com/wd/hub";
    String URL = "https://www.lambdatest.com/";
 
   
    @BeforeTest
    @Parameters("browser")
    public void setUp(String browser)throws MalformedURLException  
    {           
        if(browser.equalsIgnoreCase("chrome"))
        {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("browserName", "chrome");    //To specify the browser
            capabilities.setCapability("version", "70.0");      //To specify the browser version
            capabilities.setCapability("platform", "win10");        // To specify the OS
            capabilities.setCapability("build", "HandlingCookie");               //To identify the test 
            capabilities.setCapability("name", "CookieTest");
            capabilities.setCapability("network", true);        // To enable network logs
            capabilities.setCapability("visual", true);             // To enable step by step screenshot
            capabilities.setCapability("video", true);          // To enable video recording
            capabilities.setCapability("console", true);            // To capture console logs
            try {
                driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
            } catch (MalformedURLException e) {
                System.out.println("Invalid grid URL");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        else if(browser.equalsIgnoreCase("Firefox"))
        {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("browserName", "Firefox");   //To specify the browser
            capabilities.setCapability("version", "76.0");      //To specify the browser version
            capabilities.setCapability("platform", "win10");        // To specify the OS
            capabilities.setCapability("build", " HandlingCookie"); //To identify the test
            capabilities.setCapability("name", " CookieTest");
            capabilities.setCapability("network", true);        // To enable network logs
            capabilities.setCapability("visual", true);             // To enable step by step screenshot
            capabilities.setCapability("video", true);                        // To enable video recording
            capabilities.setCapability("console", true);            // To capture console logs
            try {
                driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
            } catch (MalformedURLException e) {
                System.out.println("Invalid grid URL");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
 
    @Test
    public void getCookieInformation()
    {
        System.out.println("=====Getting cookie information Test started======");
        driver.get(URL);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        Set<Cookie> cookiesList =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesList)
        {
            System.out.println(getcookies);
        }
        System.out.println("=====Getting cookie information Test has ended======");         
        
    }
    
    @Test
    public void addCookie() {
        boolean status = false;
 
        System.out.println("=====Adding a cookie Test started======");
        driver.get(URL);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        Cookie cname = new Cookie("myCookie", "12345678999");
        driver.manage().addCookie(cname);
 
        //retrieve the cookies to view the newly added cookie
        Set<Cookie> cookiesList =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesList) {
            System.out.println(getcookies);
            if(getcookies.getName().equals("myCookie")) {
                status = true;
                System.out.println("The cookie has been added");
            }
            else
                Assert.assertFalse(false, "The cookie hasnt been added");
        }
        System.out.println("=====Adding a new cookie Test has ended======");            
    }
    
    @Test
    public void deleteSpecificCookie()
    {
        System.out.println("=====Deleting a specific cookie Test started======");
        driver.get(URL);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        
        Cookie cname = new Cookie("myCookie1", "abcdefj");
        driver.manage().addCookie(cname);
 
        driver.manage().deleteCookie(cname);
        Set<Cookie> cookiesListNew =  driver.manage().getCookies();
        for(Cookie getcookies :cookiesListNew)
        {
            System.out.println(getcookies );
        }
        System.out.println("=====Deleting a specific cookie Test has ended======");         
    }
    
    @Test
    public void deleteAllCookies()
    {
        System.out.println("=====Deleting all cookies Test started======");
        driver.get(URL);
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        driver.manage().deleteAllCookies();
        Set<Cookie> cookiesListNew =  driver.manage().getCookies();
        cookiesListNew.size();
        System.out.println("The size is "+cookiesListNew);
        System.out.println("=====Deleting all cookies Test has ended======");           
        
    }
    @AfterTest
    public void tearDown()
    {
        driver.quit();
    }
}
```

As seen above, there are no logic changes, and most of the implementation remains unchanged. However, instead of the local Selenium WebDriver, the Remote WebDriver is used for accessing the cloud-based Selenium Grid.

Since we have four tests in the test suite, we leverage parallel testing in TestNG Selenium to realize parallelism at the Thread level. Shown below is the testng.xml file that runs tests under the @Test annotation in parallel. In addition, you can check out more TestNG Learning Hub on LambdaTest to gain insights into the TestNG framework.

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="tests">
<test name="ChromeBrowserTest">
<parameter name="browser" value="chrome"/>
<classes>
<class name="Pages.HandleCookies">
</class>
</classes>
</test>
</suite>
```

Below is the test execution status of our tests in Eclipse:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hehs8tyuicu506ewx19.png)

To run this test in the LambdaTest platform, right-click on the testng.xml that you have created in the IDE. Click Run As –> TestNG Suite. With this, the test would be triggered on the LambdaTest platform.

Shown below is the console output, which indicates that the test execution was successful:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fmtip4128myc9bcaxfp7.png)

Hop on to the [Automation Dashboard on LambdaTest](https://automation.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=feb11_sb&utm_term=sb&utm_content=blog) for checking the status of the test execution:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4bthdj6ac0gq49b34rk3.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6vf6ctb3ujdgpnieoj8.png)

With this we have demonstrated the major Selenium cookies APIs that can be used for performing operations on the cookies.

Here’s a short glimpse of the Selenium Java 101 certification from LambdaTest:

{% youtube vUxfvuAI7kE %}

***Did you know? [Random Date Generator](https://www.lambdatest.com/free-online-tools/random-date-generator?utm_source=devto&utm_medium=organic&utm_campaign=jul14_sb&utm_term=sb&utm_content=blog) allows users to randomly select a day, month, and year from any point in time. In addition, users can enter ranges of years they want and pick numbers up to 100.***

## It’s a Wrap


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18buipisnxjx1xw3i4r4.gif)

To summarize, we deep-dived into the various aspects of cookies primarily used for website owners to track the user's visits or activity. Selenium provides methods (or APIs) using which you can perform various actions on the cookies. We demonstrated how to get cookies in Selenium, how to delete all the cookies in Selenium, how to delete a certain cookie, and more.
Rather than performing Selenium automation testing on a local Selenium Grid, it is recommended to expedite the test execution using a cloud-based Selenium grid like LambdaTest. It lets you run Selenium tests at scale on 3,000+ browsers and operating systems and also lets you [app test automation](https://www.lambdatest.com/app-test-automation?utm_source=devto&utm_medium=organic&utm_campaign=mar17_sb&utm_term=sb&utm_content=blog) for your mobile apps.

I hope you find this article very useful and informative. I would love to hear how you use Selenium cookies API for large-scale websites (or web apps). Please feel free to share this blog with your friends and colleagues.

Happy Testing…!