Features

How To Handle Cookies in Selenium WebDriver

  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn
  • Share on HackerNews


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 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.

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.

    Copy code
    # 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
    Copy code
    # Returns the cookie according to a name
    cookie = driver.get_cookie(cookie_name)
    # Returns a list of all Cookies
    cookies = driver.get_cookies()
    Copy code
    $driver->manage()->getCookie($cookieName);
    Copy code
    // Returns the cookie according to a name
    
    driver.manage().getCookieNamed(cookieName);
    // Returns a list of all Cookies
    
    driver.manage().getCookies();
    Copy code
    // 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);
    });
    Copy code
    // 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:

    Copy code
    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
    Copy code
    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
    Copy code
    $driver->manage()->addCookie(['name' => 'newCookieKey, 'value' => 'newCookieValue']);
    Copy code
    import org.openqa.selenium.Cookie;
    Cookie cname = new Cookie("newCookieKey", "newCookieValue");
    driver.manage().addCookie();
    Copy code
    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()
    })();
    Copy code
    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.

    Copy code
    # Delete a specific cookie by name
    
    driver.manage.delete_cookie(cookie_name)
    # Delete all cookies
    
    driver.manage.delete_all_cookies
    
    Copy code
    # Delete a specific cookie by name
    driver.delete_cookie(cookie_name)
    # Delete all cookies
    driver.delete_all_cookies()
    Copy code
    $driver->manage()->deleteCookie($cookieName);
    Copy code
    // Delete a specific cookie by name
    
    driver.manage().deleteCookie(cookieName);
    // Delete all cookies
    
    driver.manage().deleteAllCookies();
    Copy code
    // Delete a specific cookie by name
    
    await driver.manage().deleteCookie(cookieName);
    // Delete all cookies
    
    await driver.manage().deleteAllCookies();
    Copy code
    // 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:

Copy code
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:

Copy code
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, 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:

Copy code
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:

Copy code
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.

Copy code
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()
  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn
  • Share on HackerNews
TestingBot Logo

Sign up for a Free Trial

Start testing your apps with TestingBot.

No credit card required.

Other Articles

How to use the Actions Class In Selenium

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

Read more
Handling Captcha during Automated Testing

We will discuss possible solutions to run automated tests with Captcha enabled websites.

Read more
Cypress and Cucumber Browser Testing

Cypress and Cucumber is a great combination to write clean and precise end-to-end browser tests.

Read more
TestNG automation with Selenium

TestNG is a popular Java Test Framework which allows you to write clean Selenium tests with built-in parallelisation.

Read more

Why would you choose TestingBot instead of an other company like SauceLabs or BrowserStack?

Read more

With a large number of different browsers platforms and mobile devices it is very important to make sure your website looks and behaves the way you want it to across all these different browsers.

Read more