---
title: How to Handle Cookies in Selenium WebDriver
description: Handling cookies with Selenium WebDriver is a common task, since most
  websites use cookies. In this guide, we'll show you how to do this with Selenium.
source_url:
  html: https://testingbot.com/resources/articles/handling-cookies-with-selenium
  md: https://testingbot.com/resources/articles/handling-cookies-with-selenium.md
---

![How to Handle Cookies in Selenium WebDriver](https://testingbot.com/assets/resources/articles/9.webp)

# How To Handle Cookies in Selenium WebDriver

Handling cookies with Selenium WebDriver is a common task, since most websites use cookies. In this guide, we'll show you how to do this with Selenium.

By [Jochen D.](https://testingbot.com/about/jochen-d)2021-08-27Updated 2026-08-31

 Share on Facebook 

 Share on Twitter 

 Post on Reddit 

 Share link 

A cookie is a piece of information which saves information on the hard disk of the user's computer.   
 Websites can use it to track users, save preferences for the user or save any other data.   
 Cookies can be set to expire at a certain time, or to be saved permanently (at least until the user decides to wipe all cookies).

Handling cookies during your [automated testing](https://testingbot.com/features) is a common task, since most websites are using cookies to track and retain specific user information.   
 We will discuss several topics related to handling cookies while running automated tests.   
 You can also read the Selenium documentation regarding [working with cookies](https://www.selenium.dev/documentation/support_packages/working_with_cookies/).

## Table of Contents

- [Why do I need to handle cookies during automated testing?](https://testingbot.com#why)
- [How to use cookies with Selenium?](https://testingbot.com#use)
- [How to use the Selenium Cookie API with a Selenium Grid?](https://testingbot.com#grid)
- [How can I clear the browser cache automatically?](https://testingbot.com#clear)

## Why do I need to handle cookies during automated testing?

Websites may use cookies for different purposes, including saving data during a visitor session.

A potential problem might happen while running automated tests. The website under test might be saving specific data in the same cookie for multiple tests.

For example, let's say you are testing a shopping cart by adding an item. If one test adds the item to the cart, data might be saved in a cookie.

The second test might have logic which assumes that the cart is empty.   
 The cookie from the first test is still stored however, resulting in a test failure for the second test.

It's important to make sure that your tests always start from a pristine state, without any previous test data.

> At TestingBot, we make sure every test start from a pristine, single-use virtual machine.

### Anatomy of a cookie

A cookie may contain the following data:

- **Name** : This flag contains the name of the cookie.
- **Value** : This flag contains the value of the cookie.
- **Domain** : This determines on which domain the cookie resides.
- **Path** : This flag contains the URL required in the requested URL.
- **Expires / Max-Age** : The expiration date or the maximum age of the cookie.
- **HttpOnly** : Should this cookie be used only over HTTP?
- **Secure** : This determines if the cookie can only be sent over HTTPS.
- **SameSite** : This flag contains the values (strict or lax) if the cookie is using the experimental SameSite attribute.

#### Strict Cookie

When the `sameSite` attribute is set to Strict, cookies will not be sent to third-party websites.

#### Lax Cookie

When the `sameSite` attribute is set to Lax, cookies will be sent with GET requests to third-party websites.

## How to use cookies with Selenium?

Selenium WebDriver offers various methods to interact with cookies:

- **Get cookie** : 

Gets all cookies or a specific cookie, by name, for the current domain. You can use this to get the value, or check if the cookie exists.

[Ruby](https://testingbot.com#) [Python](https://testingbot.com#) [PHP](https://testingbot.com#) [Java](https://testingbot.com#) [Node](https://testingbot.com#) [C#](https://testingbot.com#)

```ruby
# Returns the cookie according to a name
cookie = driver.manage.cookie_named(cookie_name)
# Returns a list of all Cookies
cookies = driver.manage.all_cookies
```

```python
# Returns the cookie according to a name
cookie = driver.get_cookie(cookie_name)
# Returns a list of all Cookies
cookies = driver.get_cookies()
```

```php
$driver->manage()->getCookie($cookieName);
```

```java
// Returns the cookie according to a name
driver.manage().getCookieNamed(cookieName);
// Returns a list of all Cookies
driver.manage().getCookies();
```

```javascript
// Returns the cookie according to a name
driver.manage().getCookie(cookieName).then(function (cookie) {
	console.log(cookie);
});
// Returns a list of all Cookies
driver.manage().getCookies().then(function (cookies) {
 	console.log(cookies);
});
```

```csharp
// Returns the cookie according to a name
var cookie = driver.Manage().Cookies.GetCookieNamed(cookieName);
// Returns a list of all Cookies
var cookies = driver.Manage().Cookies.AllCookies;
```

- **Add cookie** : 

Adds a cookie for the current domain:

[Ruby](https://testingbot.com#) [Python](https://testingbot.com#) [PHP](https://testingbot.com#) [Java](https://testingbot.com#) [Node](https://testingbot.com#) [C#](https://testingbot.com#)

```ruby
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://testingbot.com'
  # Add a cookie, named "newCookieKey" with value "newCookieValue"
  driver.manage.add_cookie(name: "newCookieKey", value: "newCookieValue")
ensure
  driver.quit
end
```

```python
from selenium import webdriver
driver = webdriver.Chrome()

driver.get("https://testingbot.com")

# Add a cookie, named "newCookieKey" with value "newCookieValue"
driver.add_cookie({"name": "newCookieKey", "value": "newCookieValue"})
driver.quit
```

```php
$driver->manage()->addCookie(['name' => 'newCookieKey, 'value' => 'newCookieValue']);
```

```java
import org.openqa.selenium.Cookie;
Cookie cname = new Cookie("newCookieKey", "newCookieValue");
driver.manage().addCookie();
```

```javascript
const {Builder} = require('selenium-webdriver');
(async function example() {
    let driver = new Builder()
        .forBrowser('chrome')
        .build();

    await driver.get('https://testingbot.com');

    // Add a cookie, named "newCookieKey" with value "newCookieValue"
    await driver.manage().addCookie({name:'newCookieKey', value: 'newCookieValue'});
    await driver.quit()
})();
```

```csharp
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace AddCookie {
 class AddCookie {
  public static void Main(string[] args) {
   IWebDriver driver = new ChromeDriver();
   try {
    // Navigate to Url
    driver.Navigate().GoToUrl("https://testingbot.com");

    // Add a cookie, named "newCookieKey" with value "newCookieValue"
    driver.Manage().Cookies.AddCookie(new Cookie("newCookieKey", "newCookieValue"));
   } finally {
    driver.Quit();
   }
  }
 }
}
```

- **Delete cookie** : 

Deletes a specific cookie, or all cookies for the current domain.

[Ruby](https://testingbot.com#) [Python](https://testingbot.com#) [PHP](https://testingbot.com#) [Java](https://testingbot.com#) [Node](https://testingbot.com#) [C#](https://testingbot.com#)

```ruby
# Delete a specific cookie by name
driver.manage.delete_cookie(cookie_name)
# Delete all cookies
driver.manage.delete_all_cookies
```

```python
# Delete a specific cookie by name
driver.delete_cookie(cookie_name)
# Delete all cookies
driver.delete_all_cookies()
```

```php
$driver->manage()->deleteCookie($cookieName);
```

```java
// Delete a specific cookie by name
driver.manage().deleteCookie(cookieName);
// Delete all cookies
driver.manage().deleteAllCookies();
```

```javascript
// Delete a specific cookie by name
await driver.manage().deleteCookie(cookieName);
// Delete all cookies
await driver.manage().deleteAllCookies();
```

```csharp
// Delete a specific cookie by name
driver.Manage().Cookies.DeleteCookie(cookieName);
// Delete all cookies
driver.Manage().Cookies.DeleteAllCookies();
```

### Iterate over all cookies

Let's see another example where we iterate over all available cookies and print the contents of each cookie, for debugging purposes:

```java
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class CookiesExample {
    public static void main(String args[]) {
 				System.setProperty("webdriver.chrome.driver", "ChromeDriver Path");
        WebDriver driver = new ChromeDriver();
        String url ="https://testingbot.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();
    }
}
```

You can modify the loop to delete specific cookies, or write the contents to a file as a test artifact.

### Replacing cookies

To replace a cookie during an automated test, we suggest deleting the specific cookie and setting a new cookie with the same name.

### Expiring cookies

Cookies have a `expiry` flag which browsers use to automatically expire specific cookies.   
 To set a cookie with an expiration date via Selenium, please use the `expiry` argument in the Cookie constructor:

```java
Date expiry = new Date();
driver.manage().addCookie(
                new Cookie(name, value, domain, path, expiry));
```

## How to use the Selenium Cookie API with a Selenium Grid?

To use the Selenium Cookie API with a [Selenium Grid](https://testingbot.com/support/web-automate/selenium), you can use RemoteWebdriver and call the Selenium Cookie methods on the RemoteWebDriver object.

Instead of running your Selenium tests on your local computer, you might want to run tests on a (Cloud) Selenium grid. This offers great advantages, such as:

- **Increased scalability** : run tests in parallel on a Cloud grid such as TestingBot.
- **Increased reliability** : tests can be retried automatically when a connection/OS issue is detected.
- **Performance** : you can run the browser tests on more powerful computers than your own computer.

Please see the example below on how to clear cookies during a TestingBot test:

```java
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;

public class JavaSample {

  public static final String URL = "https://key:secret@hub.testingbot.com/wd/hub";

  public static void main(String[] args) throws Exception {

	DesiredCapabilities caps = new DesiredCapabilities();
	caps.setCapability("browserName", "IE");
	caps.setCapability("version", "11");
	caps.setCapability("platform", "WIN10");
	caps.setCapability("name", "My First Test");

	WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
	driver.get("http://www.google.com/ncr");
	WebElement element = driver.findElement(By.name("q"));

	element.sendKeys("TestingBot");
	element.submit();

	System.out.println(driver.getTitle());
	driver.quit();
  }
}

public void deleteSpecificCookie(RemoteWebDriver driver, String cookieName) {
	driver.manage().deleteCookie(cookieName);
}

public void deleteAllCookies(RemoteWebDriver driver) {
    System.out.println("Deleting all cookies");
    driver.manage().deleteAllCookies();  
}
```

## How can I clear the browser cache automatically?

In between automated tests, you might want to clear the cache of your browser, which includes history state, cookies and other saved data.

It's important for tests to be able to start with a pristine state.   
 If there are leftover artifacts from previous test sessions, for example an item still in a shopping cart, the test's assertion might fail.

We'll show you two solutions to clear the browser's cache automatically:

### DeleteAllCookies with Selenium WebDriver

Selenium WebDriver offers a Selenium Cookie API which allows you to delete all cookies, the method is called `webDriver.Manage().Cookies.DeleteAllCookies`:

```java
public void clearBrowserCache() {
	webDriver.Manage().Cookies.DeleteAllCookies(); // delete all cookies
	thread.Sleep(5000); // wait a bit before continuing
}
```

### Clear Browser Data with Chromedriver

You can use Chromedriver to clear the browser cache. Of course, this only works when testing on Chrome.   
 If you are testing on a different browser, we recommend using the Selenium Cookie API.

```python
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome("path/to/chromedriver.exe")

def delete_cache():
    driver.get('chrome://settings/clearBrowserData') # for old chromedriver versions use chrome://settings/cleardriverData
    time.sleep(3)
    actions = ActionChains(driver) 
    actions.send_keys(Keys.TAB * 3 + Keys.DOWN * 3) # send the right keys to navigate to the view
    actions.perform()
    time.sleep(2)
    actions = ActionChains(driver) 
    actions.send_keys(Keys.TAB * 4 + Keys.ENTER) # confirm the action
    actions.perform()
    time.sleep(3) # wait a bit to finish
    driver.switch_to.window(driver.window_handles[0]) # switch back to your test case
delete_cache()
```

Topics [Selenium](https://testingbot.com/resources/articles/topic/selenium) 

## Sidebar

### TestingBot Cloud Testing

Run automated, manual and visual tests on remote browsers and devices. Sign up for a free trial.

[Free Trial](https://testingbot.com/users/sign_up)

### Latest articles

[![Selenium Python Tutorial](https://testingbot.com/assets/resources/articles/51-39337d128e18d16ddec5fe39124c2302f334e0f21e06f361cfd19e0b719e8861.webp)](https://testingbot.com/resources/articles/python-selenium-web-automation-test)

#### [Selenium Python Tutorial](https://testingbot.com/resources/articles/python-selenium-web-automation-test)

Getting started with Selenium WebDriver in Python: a firs...

[Read article →](https://testingbot.com/resources/articles/python-selenium-web-automation-test)

[![Handling Exceptions with Selenium Webdriver](https://testingbot.com/assets/resources/articles/43-044fb4e2070e941fec050b38f1c4ed34a06e7c8b63c67a6b8758805869eb75be.webp)](https://testingbot.com/resources/articles/exception-handling-with-selenium)

#### [Handling Exceptions with Selenium Webdriver](https://testingbot.com/resources/articles/exception-handling-with-selenium)

The Selenium WebDriver exceptions you will actually hit, ...

[Read article →](https://testingbot.com/resources/articles/exception-handling-with-selenium)

[![ElementClickInterceptedException in Selenium](https://testingbot.com/assets/resources/articles/33-47ac7bd953d8c5e5d1274bfe324e755e37c21003cf9224b826e4833a9f1e9001.webp)](https://testingbot.com/resources/articles/selenium-elementclickinterceptedexception)

#### [ElementClickInterceptedException in Selenium](https://testingbot.com/resources/articles/selenium-elementclickinterceptedexception)

What causes an ElementClickInterceptedException in Seleni...

[Read article →](https://testingbot.com/resources/articles/selenium-elementclickinterceptedexception)

## Other Articles

[![Testing with React and Selenium](https://testingbot.com/assets/resources/articles/31-744de7cfd83a956722f63fdccfc836d4cd8ee5182785fd84f7bbabe3a40e1615.webp)](https://testingbot.com/resources/articles/react-selenium-testing "Testing with React and Selenium")

### [Testing with React and Selenium](https://testingbot.com/resources/articles/react-selenium-testing)

How to test a React site with both React Testing Library and Selenium WebDriver, and when each of the two is the right tool to reach for.

[Read article →](https://testingbot.com/resources/articles/react-selenium-testing)

[![Selenium and Generative AI](https://testingbot.com/assets/resources/articles/28-af707bf052844eb00f861bb6ebba57e6be4479dde1c78a5df4e70d2f597a8b18.webp)](https://testingbot.com/resources/articles/generative-ai-selenium "Selenium and Generative AI")

### [Selenium and Generative AI](https://testingbot.com/resources/articles/generative-ai-selenium)

How to use generative AI to produce realistic test data for Selenium runs, and why varied data uncovers bugs that fixed fixtures never will.

[Read article →](https://testingbot.com/resources/articles/generative-ai-selenium)

[![Getting Started with IntelliJ and Selenium WebDriver](https://testingbot.com/assets/resources/articles/16-511fdda6b13b4e7660736fb97eb23be9b62874f39294870fb66212303d530cca.webp)](https://testingbot.com/resources/articles/getting-started-with-webdriver-in-java-using-intellij "Getting Started with IntelliJ and Selenium WebDriver")

### [Getting Started with IntelliJ and Selenium WebDriver](https://testingbot.com/resources/articles/getting-started-with-webdriver-in-java-using-intellij)

How to set up IntelliJ IDEA for Selenium WebDriver: the project, browser drivers, JUnit, and running the resulting tests in the cloud.

[Read article →](https://testingbot.com/resources/articles/getting-started-with-webdriver-in-java-using-intellij)

[![How to use the Actions Class In Selenium](https://testingbot.com/assets/resources/articles/8-f84768dacc47dbc268338db641c2c210f5da0b9d258f4ea8592d298b015473bf.webp)](https://testingbot.com/resources/articles/what-are-selenium-actions "How to use the Actions Class In Selenium")

### [How to use the Actions Class In Selenium](https://testingbot.com/resources/articles/what-are-selenium-actions)

Selenium WebDriver comes with an Action Class, which allows you to simulate user input events, such as mouse and keyboard actions.

[Read article →](https://testingbot.com/resources/articles/what-are-selenium-actions)

## Ready to start testing?
[Start a free trial](https://testingbot.com/users/sign_up)
