1

我在 Java 6 中使用 Selenium 2.21.0。如何使用 Selenium WebDriver API 下载网页上的文件?也就是说,有一个链接会导致 Excel 文件的下载开始。我想知道如何启动该下载,确定它何时完成,然后找出文件在我的本地系统上下载到的位置。

4

2 回答 2

0

单击任何链接下载文件后,它取决于浏览器的行为,例如 Chrome 行为:默认情况下,只要用户单击任何文件的链接,它就会开始下载文件。IE 行为:IE 在窗口底部显示一个栏,并显示保存或取消文件下载的选项。FireFox 行为:这将显示一个对话框窗口并显示保存或取消文件下载的选项。 所以这可以在 FireFox Profile 的帮助下实现。并且在下载任何文件之前,您必须将文件的 MIME 类型传递给 FireFox 配置文件。 一些常用的 MIME 类型包括: 文本文件 (.txt) – 文本/纯 PDF 文件 (.pdf) – 应用程序/pdf CSV 文件 (.csv) – 文本/csv MS Excel 文件 (.xlsx) – 应用程序/vnd .openxmlformats-officedocument.spreadsheetml.sheet MS word 文件 (.docx) – application/vnd.openxmlformats-officedocument.wordprocessingml.document

这是代码:

    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.FirefoxProfile;

    public class DownloadFiles {

    public static void main(String[] args) throws InterruptedException {
    //Create FireFox Profile object
    FirefoxProfile p = new FirefoxProfile();

    //Set Location to store files after downloading.
    profile.setPreference("browser.download.folderList", 2);

   //Set preference not to file confirmation dialogue
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", 
        "application/vnd.openxmlformats-
        officedocument.spreadsheetml.sheet"); 

  // Specify the local system path where to download
     p.setPreference("browser.download.dir", "D:\\downloads");
  // Pass Profile parameters in Firefox browser
    FirefoxDriver driver = new FirefoxDriver(profile);  

    // Open APP to download application
    driver.get("http://url");

    // Click to download 
    driver.findElement(By.xpath("//html[@attribute='value']")).click();

    Thread.sleep(5000);

    driver.close();

希望它能解决您的疑问。快乐编码。

于 2017-06-24T18:31:30.343 回答
0

我特别关注 Firefox 浏览器,当访问者点击任何下载链接时,您可以使用下载选项附带弹出选项的地方。它显示了两个按钮和两个单选按钮,让我们可以选择保存并直接打开文件,而无需事后下载,如果我们发现文件有用,我们可以通过 Firefox 浏览器上方工具栏上的下载图标明确下载。所以你可以执行以下步骤

1) 点击下载链接

WebDriver driver = new FirefoxDriver();

driver.findElement(By.linkText(“somelink”)).click();

上面的代码可以帮助 WebDriver 识别对象并执行上面提到的动作

2) 单击下载链接后,Firefox 浏览器将弹出一个下载对话框,其中包含多个选项,例如保存单选按钮、打开单选按钮、确定按钮、取消按钮,您可以使用 Robot 类或WebDriver 喜欢

Robot r = new Robot();


r.KeyPress(KeyEvent.VK_TAB); 

您可以多次使用上述代码来按下选项卡按钮

r.KeyRelease(KeyEvent.VK_TAB);

你必须释放按下的键

最后执行输入

r.KeyPress(KeyEvent.VK_ENTER);

就是这样,当按下下载链接时,它将帮助您下载对象

希望对你有帮助

于 2017-06-25T14:25:23.020 回答