如何在Selenium WebDriver中自动清除浏览器缓存?

10
如何在每次测试运行前清除浏览器缓存?我尝试在创建驱动程序实例后的setUp方法中使用driver.manage().deleteAllCookies();来清除缓存,对于火狐浏览器有效,但对于IE浏览器没有用。请问是否有解决方案?请提供给我。
5个回答

13

如果您正在使用Protractor,则可以在capabilities哈希上设置'ie.ensureCleanSession':'true' - 请参见https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities。 - emery

3

使用以下代码清除IE中的缓存:

try {
    Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
} catch (IOException e) {
    e.printStackTrace();
}

在C#中对我有用,看看我的回复。 - craastad

2
使用这篇文章如何在C#中执行命令行并获取STD OUT结果,我编写了以下C#代码来删除cookies(顺带删除所有IE浏览器数据)。
public static void DeleteIECookiesAndData()
{
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "RunDll32.exe";
    p.StartInfo.Arguments = "InetCpl.cpl,ClearMyTracksByProcess 2";
    p.Start();
    p.StandardOutput.ReadToEnd();
    p.WaitForExit();
}

这并不是很美观,但它能够正常工作。也许可以移除一些部分。(如果您找到更好的方法,请告诉我)。


2

IE浏览器在每次页面加载后会清除每个元素的缓存

ieCapabilities.setCapability(InternetExplorerDriver.ENABLE_ELEMENT_CACHE_CLEANUP, true);

这将进行会话清理:
ieCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);

-1

使用Java可以实现这个功能:

protected void deleteCookie(String cookieName) {    
    String cookieDomain = CTPropertiesManager.getProperty("site.properties", "site.cookie.domain");
    try {
        //get all cookies
        Cookie cookies[] = request.getCookies();
        Cookie ctCookie=null;
        if (cookies !=null) {
            for(int i=0; i<cookies.length; i++) {
                ctCookie=cookies[i];
                if (ctCookie.getName().trim().equals(cookieName)) {
                    if ( cookieDomain != null ) {
                        ctCookie.setDomain(cookieDomain);
                    }
                    ctCookie.setPath("/ct");
                    ctCookie.setMaxAge(0);
                    response.addCookie(ctCookie);    
                }
            } //end for
        }//end if cookie
    } catch(Exception e) {
        CTLogManager.log(e);
    }
}//end deleteCookie()

清除缓存 您可以创建一个批处理文件,在测试开始之前清除浏览器或应用程序的缓存。创建批处理文件后,只需在测试开始前在您的代码中调用即可。


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