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!
3 Answers
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.
- 2,036
- 2
- 10
- 23
-
It is possible to clear cache using this post's answer further down that suggests using sendkeys https://stackoverflow.com/questions/49614217/selenium-clear-chrome-cache – Jun 23 '20 at 14:33
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.
- 701
- 6
- 12
-
`chrome://settings/cleardriverData` just lands on `chrome://settings` for me. – Marcel Wilson Jan 12 '21 at 19:32
-
Might be renamed. Can't test right now, but does `chrome://settings/clearBrowserData` work? Otherwise just go to 'chrome://settings` and click on the respective section. Check the URL and change `cleardriverData` to the new section name. – do-me Jan 13 '21 at 18:34
in step one =>
pip install keyboard
step2 : use it in your code =>
from time import sleep
self.driver.get('chrome://settings/clearBrowserData')
sleep(10)
keyboard.send("Enter")
- 1,279
- 13
- 11