How To Handle Cookies in Selenium WebDriver
Shalini Baskaran
Posted On: July 28, 2021
262607 Views
11 Min Read
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).
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. 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.
Starting your journey with Selenium WebDriver? Check out this step-by-step guide to perform Automation testing using Selenium WebDriver.
So, let’s get started biting the cookies 🙂
TABLE OF CONTENT
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.
- 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.
Here are the major functions of website cookies:
- Tracking the browsing activity of the user
- Remembering the login details of the user
- Tracking the visitor count in a website further helps the website owners identify their unique visitors every day.
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 tutorial.
Let us use the LambdaTest home page 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.
1 |
driver.manage().getCookies() |
This will retrieve details of all the stored cookies. Below is a simple script to get cookies in Selenium WebDriver:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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:
1 |
driver.manage().getCookieNamed(arg0); |
Below is a simple script for getting information about a specific cookie:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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
1 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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:
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:
1 |
driver.manage().deleteCookie(arg0); // Deletes the specific cookie |
This command is used for deleting a specific cookie that is matched using its name:
1 |
driver.manage().deleteCookieNamed(arg0); // Deletes the specific cookie by its name |
This command is used for deleting all the cookies:
1 |
driver.manage().deleteAllCookies(); // Deletes all the cookies |
Here is the same script that demonstrates how to delete a specific cookie:
The below script demonstrates how to use Selenium cookies API for deleting all the cookies:
Watch this video to understand how you can handle Cookies and perform different operations like deleting, getting the parameter values, and adding them to Selenium WebDriver using Java.
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.
Shown below is the demonstration of Selenium cookies API with the execution being performed on the LambdaTest Selenium Grid:
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.
1 2 3 4 5 6 7 8 9 10 11 |
<?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:
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:
Hop on to the Automation Dashboard on LambdaTest for checking the status of the test execution:
With this we have demonstrated the major Selenium cookies APIs that can be used for performing operations on the cookies.
This certification demonstrates your knowledge of Selenium and Java, and your expertise at automating tests for any project.
Here’s a short glimpse of the Selenium Java 101 certification from LambdaTest:
It’s a Wrap
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 3000+ browsers and operating systems.
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…!
Frequently Asked Questions
What is a cookie in Selenium?
A cookie is a small file stored on your computer when you access certain websites. Cookies are used to collect and store information about how you interact with our website and allow us to remember you even if you return to the site at a later time.
Can Selenium manipulate cookies?
Selenium provides functions to capture, manipulate and set cookies. It also provides the function to check whether a given cookie exists or not. You can interact and query Selenium cookies using the following:
- .getCookies() – returns the list of all cookies
- .getCookieNamed(“cookie name”) – returns cookie based on its name
- .addCookie(“cookie”) – creates and adds a cookie
- .deleteCookie(“cookie”) – deletes a cookie
- .deleteCookieName(“cookie name”) – deletes cookie based on its name
- .deleteAllCookies – delete all the cookies
Got Questions? Drop them on LambdaTest Community. Visit now