VISHVAMBRUTH J T
VISHVAMBRUTH J T

Reputation: 642

Selenium: Clear chrome cache

In my application I need a way to clear only the cache of the chrome browser before log out (except cookies - I do not want to delete cookies).

Can any one suggest me a way to click on the CLEAR DATA button in chrome. I have written the below code but the code is not working.

Configuration :

Chrome Version: Version 65.0.3325.181 (Official Build) (64-bit)

Selenium Version: 3.11.0

//Clear the cache for the ChromeDriver instance.
driver.get("chrome://settings/clearBrowserData");
Thread.sleep(10000);
driver.findElement(By.xpath("//*[@id='clearBrowsingDataConfirm']")).click();

enter image description here

Upvotes: 23

Views: 79707

Answers (13)

Blaise
Blaise

Reputation: 13489

Chrome supports DevTools Protocol commands like Network.clearBrowserCache (documentation).

Selenium (for Python) allows calling it like

driver.execute_cdp_cmd("Network.clearBrowserCache", {})

Upvotes: 8

Govinda Hinduja
Govinda Hinduja

Reputation: 39

Just add below code

driver.manage().deleteAllCookies();

Upvotes: 0

Pankaj
Pankaj

Reputation: 1

Getting NoSuchElement exception :

driver = new ChromeDriver(service, chromeOption());
        driver.manage().deleteAllCookies();
        driver.get("chrome://settings/clearBrowserData");
        staticWait(5);
        driver.switchTo().activeElement();
        driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();

Chrome Version : 97.0.4692.71

Upvotes: -1

msangel
msangel

Reputation: 10377

The controling protocol already have this task: https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-clearBrowserCache

And selenium v4+ have this implemented in its API:

driver.getDevTools().send(Network.clearBrowserCache());

For older versions of selenium it's still possible to call this method natively using underlying protocol:

private void clearCache(ChromeDriverService service, WebDriver driver) throws IOException {
        Map<String, Object> commandParams = new HashMap<>();
        commandParams.put("cmd", "Network.clearBrowserCache");
        commandParams.put("params", emptyMap());
        ObjectMapper objectMapper = new ObjectMapper();
        HttpClient httpClient = HttpClientBuilder.create().build();
        String command = objectMapper.writeValueAsString(commandParams);
        String u = service.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
        HttpPost request = new HttpPost(u);
        request.addHeader("content-type", "application/json");
        request.setEntity(new StringEntity(command));
        httpClient.execute(request);
    }

Note: for chromium you should use "/chromium/send_command" endpoint, for chrome: "/goog/cdp/execute". But as of my experience, these both work the same way in both chrome and chromium.

Upvotes: 0

Devin
Devin

Reputation: 71

self.driver.get('chrome://settings/clearBrowserData')
time.sleep(0.5)  # this is necessary
actions = ActionChains(self.driver)
actions.send_keys(Keys.TAB * 7 + Keys.ENTER)
actions.perform()

Upvotes: 0

Balt
Balt

Reputation: 13

The correct solution is deprecated, I've solved the problem by following this guide:

https://www.browserstack.com/guide/how-to-handle-cookies-in-selenium#:~:text=Navigate%20to%20the%20chrome%20settings,to%20open%20Chrome%20Developer%20Tools.

Specifically, using the command:

driver.manage().deleteAllCookies();

Upvotes: 0

Marcel Wilson
Marcel Wilson

Reputation: 4522

Method #1 worked for me in clearing JWT using python selenium and chromedriver 87.

# method 1
driver.execute_script('window.localStorage.clear()')

# method 2
driver.execute_script('window.sessionStorage.clear()')

Upvotes: 2

Soufiane Azeroual
Soufiane Azeroual

Reputation: 143

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());
}

Upvotes: 6

mamal
mamal

Reputation: 1996

this way work for me : 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")

Upvotes: 0

Pierre
Pierre

Reputation: 49

Below snippet navigates to the the chrome settings for clearing the browser data and sends a keypress to the opened dialog. Then it waits for the tab to close. You could easily do these steps manual.

IWebDriver Driver = new ChromeDriver()
Driver.Navigate().GoToUrl("chrome://settings/clearBrowserData");
Driver.SwitchTo().ActiveElement();
Driver.FindElement(By.XPath("//settings-ui")).SendKeys(Keys.Enter);
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30));
wait.Until(wd => wd.Url.StartsWith("chrome://settings"));

Upvotes: 0

Denis Rodrigues
Denis Rodrigues

Reputation: 31

Don´t forget the send keys!!!!

For Selenium Basic, below code is functional.

Function clean_cache()

    Set driver = New ChromeDriver
    Dim keys As New Selenium.keys


                driver.Get "chrome://settings/clearBrowserData"
                Sleep 5000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Tab)
                Sleep 1000
                driver.SendKeys (keys.Enter)
                Sleep 2000
                driver.Quit

End Function

Upvotes: 3

Triveni Bhalerao
Triveni Bhalerao

Reputation: 1

There is another way to click on Clear data button by traversing through shadow tree. If you are trying to locate clear data button by simply searching web element by locator strategy, it won't work due to Chrome browser version upgrade. You need to traverse through shadow tree. You can try below code to click on "Clear data" in advance tab:

package selenium.demo.test;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Test {
static WebDriver driver;
public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","F:\\selenium\\chromedriver.exe");
    // Instantiate a ChromeDriver class.       
 driver=new ChromeDriver();  
 driver.get("chrome://settings/clearBrowserData");
 WebElement root1 = driver.findElement(By.cssSelector("settings-ui"));
    // get 1st shadowroot element
    WebElement shadowRoot1 = expandRootElement(root1);

    // get 2nd parent
    WebElement root2 = shadowRoot1.findElement(By.cssSelector("settings-main"));
    // get 2nd shadowroot element
    WebElement shadowRoot2 = expandRootElement(root2);

    // get 3rd parent
    WebElement root3 = shadowRoot2.findElement(By.cssSelector("settings-basic-page"));
    // get 3rd shadowroot element
    WebElement shadowRoot3 = expandRootElement(root3);

    // get 4th parent
    WebElement root4 = shadowRoot3.findElement(By.cssSelector("settings-section > settings-privacy-page"));
    // get 4th shadowroot element
    WebElement shadowRoot4 = expandRootElement(root4);

    // get 5th parent
    WebElement root5 = shadowRoot4.findElement(By.cssSelector("settings-clear-browsing-data-dialog"));
    // get 5th shadowroot element
    WebElement shadowRoot5 = expandRootElement(root5);

    // get 6th parent
    WebElement root6 = shadowRoot5.findElement(By.cssSelector("#clearBrowsingDataDialog"));
    WebElement root7 = root6.findElement(By.cssSelector("cr-tabs[role='tablist']"));
    root7.click();

    WebElement clearDataButton = root6.findElement(By.cssSelector("#clearBrowsingDataConfirm"));


    clearDataButton.click(); // click that hard to reach button!
    driver.quit();

}
private static WebElement expandRootElement(WebElement element) {
    WebElement ele = (WebElement) ((JavascriptExecutor) driver)
            .executeScript("return arguments[0].shadowRoot", element);
    return ele;
}

}

Upvotes: 0

Sodium
Sodium

Reputation: 1066

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);
    }
}

Upvotes: 12

Related Questions