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.
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.
# 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
# Returns the cookie according to a name
cookie=driver.get_cookie(cookie_name)# Returns a list of all Cookies
cookies=driver.get_cookies()
$driver->manage()->getCookie($cookieName);
// Returns the cookie according to a name
driver.manage().getCookieNamed(cookieName);// Returns a list of all Cookies
driver.manage().getCookies();
// 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);});
// Returns the cookie according to a name
varcookie=driver.Manage().Cookies.GetCookieNamed(cookieName);// Returns a list of all Cookies
varcookies=driver.Manage().Cookies.AllCookies;
require'selenium-webdriver'driver=Selenium::WebDriver.for:chromebegindriver.get'https://testingbot.com'# Add a cookie, named "newCookieKey" with value "newCookieValue"
driver.manage.add_cookie(name: "newCookieKey",value: "newCookieValue")ensuredriver.quitend
fromseleniumimportwebdriverdriver=webdriver.Chrome()driver.get("https://testingbot.com")# Add a cookie, named "newCookieKey" with value "newCookieValue"
driver.add_cookie({"name":"newCookieKey","value":"newCookieValue"})driver.quit
const{Builder}=require('selenium-webdriver');(asyncfunctionexample(){letdriver=newBuilder().forBrowser('chrome').build();awaitdriver.get('https://testingbot.com');// Add a cookie, named "newCookieKey" with value "newCookieValue"
awaitdriver.manage().addCookie({name:'newCookieKey',value:'newCookieValue'});awaitdriver.quit()})();
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceAddCookie{classAddCookie{publicstaticvoidMain(string[]args){IWebDriverdriver=newChromeDriver();try{// Navigate to Url
driver.Navigate().GoToUrl("https://testingbot.com");// Add a cookie, named "newCookieKey" with value "newCookieValue"
driver.Manage().Cookies.AddCookie(newCookie("newCookieKey","newCookieValue"));}finally{driver.Quit();}}}}
Delete cookie:
Deletes a specific cookie, or all cookies for the current domain.
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:
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:
importorg.openqa.selenium.By;importorg.openqa.selenium.Platform;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.remote.DesiredCapabilities;importorg.openqa.selenium.remote.RemoteWebDriver;importjava.net.URL;publicclassJavaSample{publicstaticfinalStringURL="https://key:secret@hub.testingbot.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("browserName","IE");caps.setCapability("version","11");caps.setCapability("platform","WIN10");caps.setCapability("name","My First Test");WebDriverdriver=newRemoteWebDriver(newURL(URL),caps);driver.get("http://www.google.com/ncr");WebElementelement=driver.findElement(By.name("q"));element.sendKeys("TestingBot");element.submit();System.out.println(driver.getTitle());driver.quit();}}publicvoiddeleteSpecificCookie(RemoteWebDriverdriver,StringcookieName){driver.manage().deleteCookie(cookieName);}publicvoiddeleteAllCookies(RemoteWebDriverdriver){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:
publicvoidclearBrowserCache(){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.
fromselenium.webdriver.common.action_chainsimportActionChainsfromselenium.webdriver.common.keysimportKeysimporttimedriver=webdriver.Chrome("path/to/chromedriver.exe")defdelete_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()