I'm trying to clear the cache and cookies in my chrome browser (webdriver from selenium) but I can't find any solutions for specifically the chrome driver. How do I clear the cache and cookies in Python? Thanks!
Clearing LRU Cache After the use of the cache, cache_clear() can be used for clearing or invalidating the cache.
Selenium does not provide a way to delete cache, here are some workarounds. 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.
Navigate to the chrome settings page with Selenium by executing the driver. get('chrome://settings/clearBrowserData') . Click on the Clear Data button to clear the cache.
Taken from this post:
For cookies, you can use the delete_all_cookies
function:
driver.delete_all_cookies()
For cache, there isn't a direct way to do this through Selenium. If you are trying to make sure everything is cleared at the beginning of starting a Chrome driver, or when you are done, then you don't need to do anything. Every time you initialize a webdriver, it is a brand new instance with no cache, cookies, or history. Every time you terminate the driver, all these are cleared.
Cache clearing for Chromedriver with Selenium in November 2020:
Use this function which opens a new tab, choses to delete everything, confirms and goes back to previously active tab.
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.execute_script("window.open('');")
time.sleep(2)
driver.switch_to.window(driver.window_handles[-1])
time.sleep(2)
driver.get('chrome://settings/clearBrowserData') # for old chromedriver versions use cleardriverData
time.sleep(2)
actions = ActionChains(driver)
actions.send_keys(Keys.TAB * 3 + Keys.DOWN * 3) # send right combination
actions.perform()
time.sleep(2)
actions = ActionChains(driver)
actions.send_keys(Keys.TAB * 4 + Keys.ENTER) # confirm
actions.perform()
time.sleep(5) # wait some time to finish
driver.close() # close this tab
driver.switch_to.window(driver.window_handles[0]) # switch back
delete_cache()
UPDATE 01/2021: Apparently the settings section in chromedriver is subject to change. The old version was chrome://settings/cleardriverData
. In any doubt, go to chrome://settings/
, click on the browser data/cache clearing section and copy the new term.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With