您的位置:首页 > 其它

Selenium2自动化测试:让Firefox无提示地上传、下载保存文件

2017-04-13 00:00 549 查看
场景:自动化测试某Web应用的功能,需要从页面下载保存文件,供后续上传操作使用。

问题:上传文件:

driver.findElement(By.name("file1")).sendKeys("D:\\xx.cer");


注意,sendKeys前不要手欠儿地去clear,file不同于text input。

下载文件时,浏览器弹出的选择/保存文件框,Selenium2是无法控制的。手动测试时,保存文件、选择文件这些步骤问题不大,那自动化测试咋办?

解决办法:1. 使用AutoIT,查找、控制保存文件、选择文件的窗口。麻烦,不采用。

2. Firefox支持通过配置(地址栏打:about:config可看到Firefox内置支持的配置选项),来实现静默下载保存文件。

你可以通过程序来控制Firefox配置,代码如下:

DesiredCapabilities capability = new DesiredCapabilities();
capability.setBrowserName(browserName);

// http://www.educity.cn/wenda/114693.html  FirefoxProfile firefoxProfile = new FirefoxProfile();
ProfilesIni allProfiles = new ProfilesIni();

if(allProfiles.getProfile(FIREFOX_PROFILE)){
firefoxProfile = allProfiles.getProfile(FIREFOX_PROFILE);
println("服务器上找到了名为" + FIREFOX_PROFILE + "的Firefox配置。")
}else{
println("服务器上未找到名为" + FIREFOX_PROFILE + "的Firefox配置,使用客户端默认配置。")
}

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
Properties pro2 = readPropertiesFileObj("conf/temp.properties");     firefoxProfile.setPreference("browser.download.dir",pro2.getProperty("temp_dir"));
// firefox下载目录 // firefoxProfile.setPreference("browser.download.dir","D:\\Temp\\");   //免提示下载的文件类型参考: http://www.w3school.com.cn/media/media_mimeref.asp  firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/x-x509-ca-cert");

firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
   // 设置脚本无响应提示时间 =0 : 不提示
firefoxProfile.setPreference("dom.max_script_run_time", 0);

// 禁止firefox 检查组件兼容性
firefoxProfile.setPreference("extensions.checkCompatibility.temporaryThemeOverride_minAppVersion", false);

capability.setCapability(FirefoxDriver.PROFILE, firefoxProfile); driver = new RemoteWebDriver(new URL(url), capability);


说明:最终得到一个driver,使用这个driver去执行自动化测试用例,你会发现下载.cer格式的文件时,浏览器未出现任何提示,就把文件下载保存到了D:\\Temp\\下。

如果想要无提示下载保存其他格式的文件,可参考http://www.w3school.com.cn/media/media_mimeref.asp,修改 browser.helperApps.neverAsk.saveToDisk的值即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: