Selenium: Clear chrome cache

Chrome supports DevTools Protocol commands like Network.clearBrowserCache (documentation). Selenium does not have an interface for this proprietary protocol by default.

You can add support by expanding Selenium's commands:

driver.command_executor._commands['SEND_COMMAND'] = (
    'POST', '/session/$sessionId/chromium/send_command'
)

This is how you use it:

driver.execute('SEND_COMMAND', dict(cmd='Network.clearBrowserCache', params={}))

Note: this example is for Selenium for Python, but it's also possible in Selenium for other platforms in a similar way by expanding the commands.


You are using here

driver.findElement(By.xpath("//*[@id='clearBrowsingDataConfirm']")).click();

Unfortunately, this won’t work because the Chrome settings page uses Polymer and WebComponents, need to use query selector using the /deep/ combinator, so selector in this case is * /deep/ #clearBrowsingDataConfirm.

Here is workaround to your problem...you can achieve the same using either one of the following...

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

public class ClearChromeCache {

    WebDriver driver;

    /*This will clear cache*/
    @Test
    public void clearCache() throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C://WebDrivers/chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("disable-infobars");
        chromeOptions.addArguments("start-maximized");
        driver = new ChromeDriver(chromeOptions);
        driver.get("chrome://settings/clearBrowserData");
        Thread.sleep(5000);
        driver.switchTo().activeElement();
        driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();
        Thread.sleep(5000);
    }

    /*This will launch browser with cache disabled*/
    @Test
    public void launchWithoutCache() throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","C://WebDrivers/chromedriver.exe");
        DesiredCapabilities cap = DesiredCapabilities.chrome();
        cap.setCapability("applicationCacheEnabled", false);
        driver = new ChromeDriver(cap);
    }
}

YEAR 2020 Solution (using Selenium 4 alpha):

Using the devtools

    private void clearDriverCache(ChromeDriver driver) {
    driver.getDevTools().createSessionIfThereIsNotOne();
    driver.getDevTools().send(Network.clearBrowserCookies());
    // you could also use                
    // driver.getDevTools().send(Network.clearBrowserCache());
}