在 Selenium 中访问 Firefox 中的文件下载对话框。

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

我们可以在 Selenium 中访问 Firefox 中的文件下载对话框。为此,我们必须首先修改下载文件的默认存储目录。这可以通过 addpreference  方法完成。

p.addPreference("browser.download.folderList", 2);

然后,定义下载目录的新路径。

最后,我们将忽略对话框中针对文件类型(通过其 MIME 代码)的"保存到磁盘"和"打开文件"选项。可以借助 FirefoxOptions  类调用 addPreference 方法。

示例

代码实现。

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 FileDwnloadWithoutDialg{
   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-sample3.xls")).click();
   }
}

相关文章