Selenium:清除Chrome缓存

22

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

有人能建议我如何点击Chrome中的“清除数据”按钮吗? 我已经编写了下面的代码,但代码无效。

配置:

Chrome版本:Version 65.0.3325.181 (官方版本) (64位)

Selenium版本: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();

在此输入图片描述


1
你能通过开发工具识别出xpath试验的元素吗? - undetected Selenium
13个回答

12

您正在使用这里

driver.findElement(By.xpath("* /deep/ #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);
    }
}

这是我需要的东西,但我已经使用了ChromeOptions(disable-infobars),所以有没有办法同时使用ChromeOptions和DesiredCapabilities,或者有没有一种通过ChromeOptions参数禁用缓存的方法?@DebanjanB 我也标记了你,因为你可能也能为我解答。 - Bill Hileman
@BillHileman 我想你是想配置 _DesiredCapabilities_,然后使用 MutableCapabilities 中的 merge() 方法在 ChromeOptions 中进行合并。你可以在 这个讨论选项 B 中找到一个示例。 - undetected Selenium
我知道你不应该使用注释来感谢别人,但是感谢@DebanjanB。 - Bill Hileman
4
这个解决方案已经不再适用:https://developers.google.com/web/updates/2017/10/remove-shadow-piercing - user337598

7

Chrome支持像Network.clearBrowserCache这样的DevTools协议命令(文档)。

Selenium默认没有这个专有协议的接口,但您可以通过扩展Selenium的命令来添加支持:

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

这是如何使用它的方法:
driver.execute('SEND_COMMAND', dict(cmd='Network.clearBrowserCache', params={}))

注意: 这个例子是针对Python下的Selenium,但是在其他平台上使用Selenium也可以通过扩展命令类似的方式来实现。

6

2020 年解决方案(使用 Selenium 4 alpha):

使用开发人员工具

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

哪个驱动程序支持这个 get_dev_tools() 方法? - user337598
1
不是驱动程序,而是 Selenium 的版本。我认为 alpha 版本支持此功能:https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java - Soufiane Azeroual

3
不要忘记发送按键!!!
对于Selenium Basic,下面的代码是有效的。
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

这种“方法”适用于python + chromedriver + chrome 81.0。 driver.get('chrome://settings/clearBrowserData') wait_until(lambda:(driver.find_element_by_xpath('// settings-ui'))) ui = driver.find_element_by_xpath('// settings-ui') ui.send_keys(Keys.TAB)#待办事项:此对话框随时可能更改 ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.TAB) ui.send_keys(Keys.ENTER) wait_until(lambda:(driver.find_element_by_xpath('// settings-ui')),timeout = 60) - user337598

1

我使用Python Selenium和Chromedriver 87,通过方法#1成功清除了JWT。

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

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

0

只需添加以下代码

driver.manage().deleteAllCookies();


0

0
控制协议已经有这个任务: https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-clearBrowserCache 而Selenium v4+在其API中已经实现了此功能:
driver.getDevTools().send(Network.clearBrowserCache());

对于旧版本的Selenium,仍然可以使用底层协议本地调用此方法:

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

注意:对于Chromium,你应该使用"/chromium/send_command"端点,对于Chrome,则使用"/goog/cdp/execute"。 但根据我的经验,在Chrome和Chromium中这两种方式的工作方式是相同的。

0
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()

0

这种方法对我有效:

第一步 =>

pip install keyboard

步骤2:在您的代码中使用它 =>

from time import sleep
self.driver.get('chrome://settings/clearBrowserData')
sleep(10)
keyboard.send("Enter")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接