How to Clear Cache in Chrome Using Selenium Webdriver Java
Selenium is an
open-source
web-based automation tool that is
implemented using a web driver. We will be using chromedriver
because Selenium 3 enables chrome driver as the custom WebDriver implementation for the Chrome
browser.
Pre-requisites:
- chromedriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
The following 6 steps will automate the process:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver.
- Typecast web driver as Javascript executor.
- Browse the website.
- Get a clear cache button using the Javascript path.
- Execute the following script to execute and hit click:
return document.querySelector("body > settings-ui").shadowRoot.querySelector("#main").shadowRoot.querySelector("settings-basic-page").shadowRoot.querySelector("#basicPage > settings-section:nth-child(9) > settings-privacy-page").shadowRoot.querySelector("settings-clear-browsing-data-dialog").shadowRoot.querySelector("#clearBrowsingDataConfirm")
Let’s see all the above steps in the code. We will use
executeScript()
function to get clear cache button.
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; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; public class ClearCache { public static String CHROMEDRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\ChromeCache\\src\\main\\resources\\chromedriver.exe"; public static void main(String[] args) { //set Chrome webdriver System.setProperty("webdriver.chrome.driver", CHROMEDRIVER_PATH); WebDriver driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor) driver; //get the browser & Browse to the Settings String siteLink = "chrome://settings/clearBrowserData"; driver.get(siteLink); //wait for setting window to load try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } //get clear cache button WebElement clearBtn = (WebElement) js.executeScript("return document.querySelector(\"body > settings-ui\").shadowRoot.querySelector(\"#main\").shadowRoot.querySelector(\"settings-basic-page\").shadowRoot.querySelector(\"#basicPage > settings-section:nth-child(9) > settings-privacy-page\").shadowRoot.querySelector(\"settings-clear-browsing-data-dialog\").shadowRoot.querySelector(\"#clearBrowsingDataConfirm\")"); //Click clearBtn.click(); } }
Output:
- source code
- geckdriver.exe
Comments
Post a Comment