下載文件需要在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>
測試代碼結構: