如何使用 Selenium 通过点击事件下载文件?

seleniumautomation testingtesting tools更新于 2026/2/5 7:37:17

我们可以在 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");
      // 创建 FirefoxOptions 类的对象
      FirefoxOptions profile = new FirefoxOptions();
      // 使用 addPreference 方法添加浏览器首选项
      profile.addPreference(&"browser.download.folderList", 2);
      // 下载文件的位置
      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");
      // 将浏览器选项连接到 webdriver
      WebDriver driver = new FirefoxDriver(profile);
      driver.get("https://the-internet.herokuapp.com/download");
      //最大化窗口
      driver.manage().window().maximize();
      //识别元素并开始下载
      driver.findElement(By.linkText("xls-sample2.xls")).click();
   }
}

输出

此外,文件会在指定位置下载。


相关文章