如何使用 Selenium 在點選事件上下載檔案?
我們可以使用 Selenium 在點選事件中下載檔案。通常,點選下載連結時,會出現一個彈出框,其中包含檔名以及“開啟”和“儲存”選項。

要透過點選事件進行下載,需建立一個 FirefoxOptions 類物件。然後使用 addPreference 方法,我們配置瀏覽器首選項。
我們將提及下載位置與 neverAsk.openFile 和 neverAsk.saveToDisk 首選項設定。
示例
程式碼實現。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class FileDwnloadWithClick{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
// create object of FirefoxOptions class
FirefoxOptions profile = new FirefoxOptions();
// adding browser preferences with addPreference method
profile.addPreference("browser.download.folderList", 2);
// location of downloaded file
profile.addPreference("browser.download.dir",
"C:\Users\ghs6kor\Documents\Download");
profile.addPreference("browser.helperApps.neverAsk.openFile", "text/csv,application/x msexcel,application/excel," + "application/x-excel,application/vnd.ms-excel," + "image/png,image/jpeg,text/html,text/plain," + "application/msword,application/xml");
profile.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel," + "application/excel," + "application/x-excel," +"application/vnd.ms- excel,image/png,image/jpeg,text/html," +"text/plain,application/msword,application/xml");
// connecting browser options to webdriver
WebDriver driver = new FirefoxDriver(profile);
driver.get("https://the-internet.herokuapp.com/download");
//maximize window
driver.manage().window().maximize();
// identify element and start download
driver.findElement(By.linkText("xls-sample2.xls")).click();
}
}輸出

此外,檔案下載到指定位置。

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP