Clear cache before running some Selenium WebDriver tests using Java
Asked Answered
O

9

21

I am working on Selenium WebDriver automation in java programming language. In my test suite that initiates the browser window once and perform all the tests. I want to clear the browser cache before running some tests without restarting the browser. Is there any command/function, that can achieve the purpose? Thanks.

Oshinski answered 6/10, 2015 at 13:8 Comment(0)
X
17

This is what I use in Python:

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)

You can try converting these into Java. Hope this will help! :)

Xebec answered 19/6, 2019 at 3:47 Comment(0)
G
7

At least in Chrome, I strongly believe that if you go incognito you wont to have to clean up your cookies. You can set your options like following (the :

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def _options():
    options = Options()
    options.add_argument('--ignore-certificate-errors')
    #options.add_argument("--test-type")
    options.add_argument("--headless")
    options.add_argument("--incognito")
    options.add_argument('--disable-gpu') if os.name == 'nt' else None # Windows workaround
    options.add_argument("--verbose")
    return options

and call like this:

with webdriver.Chrome(options=options) as driver:
    driver.implicitly_wait(conf["implicitly_wait"])
    driver.get(conf["url"])
Galloot answered 6/1, 2019 at 14:8 Comment(1)
Not convinced its usefull for an end-to-end test, because at this point, you are no longer using the same environment as a customer would.Militiaman
A
5

For IE

DesiredCapabilities ieCap =  DesiredCapabilities.internetExplorer();
ieCap.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);

For Chrome:

https://code.google.com/p/chromedriver/issues/detail?id=583

To delete cookies:

driver.manage().deleteAllCookies();
Aforethought answered 6/10, 2015 at 14:9 Comment(1)
DesiredCapabilities has been deprecatedSalami
L
5

The following code is based on @An Khang 's answers. and it is working properly on Chrome 78.

ChromeDriver chromeDriver = new ChromeDriver();

    chromeDriver.manage().deleteAllCookies();
    chromeDriver.get("chrome://settings/clearBrowserData");
    chromeDriver.findElementByXPath("//settings-ui").sendKeys(Keys.ENTER);

    return chromeDriver;
Lise answered 29/11, 2019 at 10:4 Comment(3)
This selector no longer returns any elements in 81.0.4Militiaman
This solution worked for me, I am using chrome 86 , ThanksEmergent
This doesn't work in Chrome 87, the enter key doesn't trigger clearing the cache.Junk
U
3
    WebDriver driver = new ChromeDriver();
    driver.manage().deleteAllCookies();
    driver.get("chrome://settings/clearBrowserData");
    driver.findElement(By.xpath("//settings-ui")).sendKeys(Keys.ENTER);
Unarm answered 6/6, 2020 at 17:30 Comment(0)
I
1

On Google chrome you can use this script:

        driver.get("chrome://settings/clearBrowserData");       
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        WebElement clearData =  (WebElement) jse.executeScript("return document.querySelector(\"body > settings-ui\").shadowRoot.querySelector(\"#main\").shadowRoot.querySelector(\"settings-basic-page\").shadowRoot.querySelector(\"#basicPage > settings-section:nth-child(8) > settings-privacy-page\").shadowRoot.querySelector(\"settings-clear-browsing-data-dialog\").shadowRoot.querySelector(\"#clearBrowsingDataConfirm\")");
        ((JavascriptExecutor)driver).executeScript("arguments[0].click();", clearData);
Infiltrate answered 5/8, 2021 at 13:22 Comment(0)
B
1
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_webdriver(width: int = 1600, height: int = 1200):
try:
    global browser
    if browser is not None:
        return browser
    options = Options()
    options.add_argument('--headless')
    options.add_argument('--width=' + str(width))
    options.add_argument('--height=' + str(height))
    options.add_argument("--disable-cache")

    profile = webdriver.FirefoxProfile()
    profile.set_preference("browser.cache.disk.enable", False)
    profile.set_preference("browser.cache.memory.enable", False)
    profile.set_preference("browser.cache.offline.enable", False)
    profile.set_preference("network.http.use-cache", False)
    options.profile = profile

    browser = webdriver.Firefox(options=options)
    window_size = browser.execute_script("""
    return [window.outerWidth - window.innerWidth + arguments[0],
      window.outerHeight - window.innerHeight + arguments[1]];
    """, width, height)
    browser.set_window_size(*window_size)
    return browser
except Exception as err:
    logging.error(f"Can't install GeckoDriverManager. Error: {err}")

and use browser

    browser = get_webdriver(width=width, height=height)
    browser.delete_all_cookies()
    browser.get(url)
    wait = WebDriverWait(browser, 10)  # Maximum wait time in seconds
    wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
    await asyncio.sleep(1)

    png_image = browser.get_screenshot_as_png()
Boff answered 23/6, 2023 at 14:28 Comment(0)
A
0
import org.openqa.selenium.Keys;

you need to import the Keys in newer version and change the last line to findElement by xpath

WebDriver driver = new ChromeDriver();

driver.manage().deleteAllCookies();
driver.get("chrome://settings/clearBrowserData");
driver.findElement(By.xpath("//settings-ui")).sendKeys(Keys.ENTER);
Achitophel answered 19/3, 2021 at 12:36 Comment(3)
Isn't this exactly what Ambesh Srivastava answered?Dupleix
I only wrote it, because in newer versions the import is needed.Achitophel
Not working for Chrome v96. Other suggestions?Colicweed
R
0

what i found working for myself was adding chromium flag:

--disk-cache-size=0

not sure if it clears cache, but any cache related problems disappeared in my case

Ragamuffin answered 3/6, 2023 at 23:18 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewFire

© 2022 - 2024 — McMap. All rights reserved.