4

Is there a way to clear the browser cache using python?

I am trying to automate something that involves clearing all cache before checking the data. This is to ensure whether uncached data is showing up or not.

Please let me know if anyone has any idea on this.

I need to do it with python or anything that integrates with a pytest framework.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Aanchal
  • 43
  • 1
  • 4
  • @Thomas the tags aren't the same, and when I see the accepted answer for the "possible duplicate" it's definitely not the same question. This [question](https://stackoverflow.com/questions/32970855/clear-cache-before-running-some-selenium-webdriver-tests-using-java) is more related (see the python answer) – RMPR Oct 24 '19 at 07:50

1 Answers1

2

You can use Selenium:

  • For Chrome:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('chrome://settings/clearBrowserData')
driver.find_element_by_xpath('//settings-ui').send_keys(Keys.ENTER)
  • For Firefox:
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


dialog_selector = '#dialogOverlay-0 > groupbox:nth-child(1) > browser:nth-child(2)'

accept_dialog_script = (
    f"const browser = document.querySelector('{dialog_selector}');" +
    "browser.contentDocument.documentElement.querySelector('#clearButton').click();"
)


def get_clear_site_data_button(driver):
    return driver.find_element_by_css_selector('#clearSiteDataButton')


def get_clear_site_data_dialog(driver):
    return driver.find_element_by_css_selector(dialog_selector)


def get_clear_site_data_confirmation_button(driver):
    return driver.find_element_by_css_selector('#clearButton')


def clear_firefox_cache(driver, timeout=10):
    driver.get('about:preferences#privacy')
    wait = WebDriverWait(driver, timeout)

    # Click the "Clear Data..." button under "Cookies and Site Data".
    wait.until(get_clear_site_data_button)
    get_clear_site_data_button(driver).click()

    # Accept the "Clear Data" dialog by clicking on the "Clear" button.
    wait.until(get_clear_site_data_dialog)
    driver.execute_script(accept_dialog_script)

    # Accept the confirmation alert.
    wait.until(EC.alert_is_present())
    alert = Alert(driver)
    alert.accept()

Sources:

chrome firefox

RMPR
  • 3,368
  • 4
  • 19
  • 31