【Selenium】【Java】Selenium in JUnit ~ファイルダウンロード編~

 ■ ダウンロードの確認

Firefox

@Test
public void DownloadSample() throws Exception {

   // プロファイルの作成
   FirefoxProfile profile = new FirefoxProfile();
   // ダウンロードするファイルの保存先フォルダを指定
   //  0:デスクトップ 1:ダウンロードフォルダ 2:ダウンロードに指定された最後のフォルダ
   profile.setPreference("browser.download.folderList", 0);
   // ダウンロードするファイルの保存先フォルダが指定してあればそれを使う
   profile.setPreference("browser.download.useDownloadDir", true);
   // ダウンロードフォルダ
   profile.setPreference("browser.download.dir","c:/temp");
   // ★ここが大事★
   // 指定したmimeタイプは有無を言わさずダウンロードする
   profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
         "text/html, text/plain, application/vnd.ms-excel, text/csv, application/zip, text/comma-separated-values, application/octet-stream");
   // ダウンロードダイアログを見せないようにする
   profile.setPreference("browser.download.manager.showWhenStarting", false);

   // 作成したプロファイルでFirefox(のドライバー)を起動する
   driver = new FirefoxDriver(profile);
   driver.get("http://localhost:8080/");

   FileLoader(driver);

   driver.quit();
}

private static void FileLoader(WebDriver driver) throws InterruptedException {
   WebElement download = driver.findElement(By.linkText("Download"));
   download.click();

   // ★このスリープがかなり大事★
   Thread.sleep(3000);

   // ダウンロードファイルの確認処理
}

 参考文献

Firefox
http://design-ambience.com/wordpress/?p=114
http://www.atmarkit.co.jp/ait/articles/1211/07/news009_2.html
https://teratail.com/questions/1056
IE
http://sqa.stackexchange.com/questions/3169/downloading-a-file-in-internet-explorer-through-selenium
Chrome
http://anahorny.blogspot.jp/2013/04/disable-save-as-dialog-in-selenium.html
https://gist.github.com/cnhappier/d783922dd208f60fd974
https://www.snip2code.com/Snippet/298485/Disable-Save-As-dialog-in-Selenium-Chrom