Clearing Cookies & Cache in Selenium

Shahnaz Shariff
Tenets
Published in
2 min readJul 21, 2020

Selenium does not provide a way to delete cache, here are some workarounds.

Source

There are a few ways in which cache can be deleted using Selenium Webdriver for regular Chrome browsers.

For instance, here they explain how selenium can be used to clear cache like a real user i.e., by navigating to chrome settings.

However, we are looking for an automated way to clear cache which works for headed & headless chrome.

4 ways to clear cache & cookies

Method 1

window.localStorage.clear()

Method 2

window.sessionStorage.clear()

Method 3

driver.delete_all_cookies()

Method 4

Use the below command as a Chrome option:

— disk-cache-size=0

By setting cache to 0, it’s effectively never used. There’s browser memory and disk memory. By using this option, we save the memory used on writing operations to the disk. The browser will still be loading page from its memory.

How to verify if it works?

Monitor the memory consumed by chrome processes while running the test script before and after applying the hack.

For Linux systems with Sysstat installed, the command below can be used to monitor the memory usage for chrome processes.

pidtstat -r Chrome 1

Note: This includes chromedriver as well but it can be filtered out later.

That’s it folks! Thanks for reading.

--

--

Tenets
Tenets

Published in Tenets

A community of lifelong learners curating stories on tech, finance & life lessons. Follow to join our community.