如何使用 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();
   }
}

输出

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

更新于: 28-12-2020

已浏览 1 千次+

开启您职业生涯

完成课程以获得认证

开始
广告