selenium测试(Java)--下载文件(十六)
下载文件需要在Firefox 的profile属性中配置一些参数,如下面的代码:
1 package com.test.download; 2 3 import java.io.File; 4 5 import org.openqa.selenium.By; 6 import org.openqa.selenium.JavascriptExecutor; 7 import org.openqa.selenium.WebDriver; 8 import org.openqa.selenium.firefox.FirefoxDriver; 9 import org.openqa.selenium.firefox.FirefoxProfile; 10 11 public class DownloadTest { 12 13 public static void main(String[] args) { 14 15 FirefoxProfile profile = new FirefoxProfile(); 16 17 // 可以在Firefox浏览器地址栏中输入about:config来查看属性 18 // 设置下载文件放置路径,注意如果是windows环境一定要用\\,用/不行 19 String path = "D:\\10-selenium\\workspace\\SeleniumTest\\src\\com\\test\\download\\down"; 20 String downloadFilePath = path + "\\d.exe"; 21 File file = new File(downloadFilePath); 22 if (file.exists()) { 23 file.delete(); 24 } 25 26 // 配置响应下载参数 27 profile.setPreference("browser.download.dir", path);// 下载路径 28 profile.setPreference("browser.download.folderList", 2);// 2为保存在指定路径,0代表默认路径 29 profile.setPreference("browser.download.manager.showWhenStarting", false);// 是否显示开始 30 // 禁止弹出保存框,value是文件格式,如zip文件 31 profile.setPreference("browser.helperApps.neverAsk.saveToDisk", 32 "application/zip,text/plain,application/vnd.ms-excel,text/csv,text/comma-separated-values,application/octet-stream,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//关于类型:可以参考http://www.w3school.com.cn/media/media_mimeref.asp 33 34 WebDriver driver = new FirefoxDriver(profile); 35 driver.get("file:///D:/10-selenium/workspace/SeleniumTest/src/com/test/download/download.html"); 36 driver.manage().window().maximize(); 37 38 driver.findElement(By.linkText("下载")).click(); 39 40 waitTime(3000); 41 String js_exist = "alert(\"download successfully\")"; 42 String js_not_exist = "alert(\"download unsuccessfully\")"; 43 44 if (file.exists()) { 45 ((JavascriptExecutor) driver).executeScript(js_exist); 46 } else { 47 ((JavascriptExecutor) driver).executeScript(js_not_exist); 48 } 49 50 waitTime(5000); 51 // driver.quit(); 52 53 } 54 55 static public void waitTime(int time) { 56 57 try { 58 Thread.sleep(time); 59 } catch (InterruptedException e) { 60 // TODO Auto-generated catch block 61 e.printStackTrace(); 62 } 63 } 64 65 }
使用到的页面例子:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>download</title> 6 </head> 7 <body> 8 <a href="d.exe">下载</a> 9 </body> 10 </html>
测试代码结构:
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/5676538.html