google-chrome - Selenium:清除 chrome 缓存

标签 google-chrome selenium

在我的应用程序中,我需要一种方法在注销之前仅清除 Chrome 浏览器的缓存(Cookie 除外 - 我不想删除 Cookie)。

有人可以建议我一种方法来单击 chrome 中的“清除数据”按钮吗? 我已经编写了下面的代码,但该代码不起作用。

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

最佳答案

您在这里使用

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

不幸的是,这不起作用,因为 Chrome 设置页面使用 PolymerWebComponents,需要使用/deep/组合器的查询选择器,因此此选择器案例为*/deep/#clearBrowsingDataConfirm

这是解决您的问题的方法...您可以使用以下任一方法来实现相同的目的...

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

关于google-chrome - Selenium:清除 chrome 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614217/

相关文章:

java - Selenium html webdriver 无法定位元素

Javascript在网页上执行js,例如chrome控制台

javascript - Chrome 书签可以包含大量 JavaScript 吗?

ruby - 从 Cucumber/Capybara 测试中执行 JavaScript

java - 传递 ChromeOptions 而不实例化新的 WebDriver

python - 通过循环抓取不同的日期

javascript - 在 Protractor 中启用元素时单击

macos - 如何在 webkit OSX 中禁用回滚?

javascript - 在 Javascript 中,如何在不移动鼠标的情况下强制更改鼠标光标?

html - 使用 css(使用 chrome)禁用打印机默认边距?