1. 程式人生 > >selenium測試(Java)--下載文件(十六)

selenium測試(Java)--下載文件(十六)

void nload when ati quit new selenium max separate

下載文件需要在Firefox 的profile屬性中配置一些參數,如下面的代碼:

package com.test.download;

import java.io.File;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class DownloadTest { public static void main(String[] args) { FirefoxProfile profile = new FirefoxProfile(); // 可以在Firefox瀏覽器地址欄中輸入about:config來查看屬性 // 設置下載文件放置路徑,註意如果是windows環境一定要用\\,用/不行 String path = "D:\\10-selenium\\workspace\\SeleniumTest\\src\\com\\test\\download\\down"; String downloadFilePath
= path + "\\d.exe"; File file = new File(downloadFilePath); if (file.exists()) { file.delete(); } // 配置響應下載參數 profile.setPreference("browser.download.dir", path);// 下載路徑 profile.setPreference("browser.download.folderList", 2);// 2為保存在指定路徑,0代表默認路徑
profile.setPreference("browser.download.manager.showWhenStarting", false);// 是否顯示開始 // 禁止彈出保存框,value是文件格式,如zip文件 profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "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 WebDriver driver = new FirefoxDriver(profile); driver.get("file:///D:/10-selenium/workspace/SeleniumTest/src/com/test/download/download.html"); driver.manage().window().maximize(); driver.findElement(By.linkText("下載")).click(); waitTime(3000); String js_exist = "alert(\"download successfully\")"; String js_not_exist = "alert(\"download unsuccessfully\")"; if (file.exists()) { ((JavascriptExecutor) driver).executeScript(js_exist); } else { ((JavascriptExecutor) driver).executeScript(js_not_exist); } waitTime(5000); // driver.quit(); } static public void waitTime(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

使用到的頁面例子:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>download</title>
</head>
<body>
<a href="d.exe">下載</a>
</body>
</html>

測試代碼結構:

技術分享

selenium測試(Java)--下載文件(十六)