【问题标题】:How to download any file and save it to the desired location using Selenium Webdriver如何使用 Selenium Webdriver 下载任何文件并将其保存到所需位置
【发布时间】:2013-05-20 17:56:54
【问题描述】:

我必须使用下面给出的 Selenium Webdriver 执行以下任务。

  1. 点击任何链接/按钮开始下载任何文件(文件类型可以是任何图像、pdf、jar 等)
  2. 如果出现弹出窗口,请单击“保存”(例如 http://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar
  3. 提供保存该文件所需的位置。

任何人都可以分享,我们如何使用 Java 来实现?

【问题讨论】:

  • 您可以使用 AutoIT 来非常顺利地完成此操作,而无需更改或引用任何配置或属性文件,您可以参考我对similar post的回复
  • Sikulixapi 将允许您访问对话框并在您想要保存它的框中键入并按下保存按钮。 sikulix.com

标签: selenium selenium-webdriver


【解决方案1】:

您可以使用以下代码将文件保存到所需位置。

package popups;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class FileDownloadPopup 
{
    WebDriver driver;
    FirefoxProfile prof = new FirefoxProfile();
    FirefoxOptions options = new FirefoxOptions();

    @BeforeMethod
    public void setEnvi() 
    {
        System.setProperty("webdriver.gecko.driver", "E:\\Selenium Dependencies\\BrowserExecutables\\geckodriver_win64_v0.21.0.exe");
        prof.setPreference("browser.download.dir","E:\\Downloads");
        prof.setPreference("browser.download.folderList", 2);
        prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        options.setProfile(prof);
        driver = new FirefoxDriver(options);
        driver.get("http://file-examples.com/index.php/sample-documents-download/sample-xls-download/");
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    }

    @Test
    public void FDPP()
    {
        driver.findElement(By.xpath("(//a[text()='Download sample xlsx file'])[1]")).click();
    }

    @AfterMethod
    public void closeEnvi()
    {
        driver.close();
    }

}

【讨论】:

    【解决方案2】:

    如果您使用的是 Java 和 Chromdriver,我开发了一个 library,它可以让您的下载更加轻松。

    在其功能中,您可以在一行代码中设置下载目录并验证您的文件是否已成功下载:

    @Test
    void downloadAttachTest() throws InterruptedException {
        adamInternetPage.navigateToPage(driver);
        seleniumDownloadKPI.fileDownloadKPI(
                adamInternetPage.getFileDownloadLink(), "SpeedTest_16MB.dat");
        waitBeforeClosingBrowser();
    }
    

    【讨论】:

      【解决方案3】:

      一种可能的解决方案是通过 Selenium 获取文件的 URL,创建(非 Selenium)连接,将 Selenium 的 cookie 复制到连接(如果需要),然后下载文件。大多数语言都有用于执行 HTTP 请求的 API(或库)。例如,要在 Java 中完成此操作,您可以使用 URL.openConnection():

      String link = linkElement.getAttribute("href");
      URL url = new URL(link);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
      httpURLConnection.setRequestMethod("GET");
      

      您可能需要复制 Selenium 的 cookie 以模仿 Selenium 用户(例如,如果您正在测试需要登录的网站)。

      Set<Cookie> cookies = webDriver.manager().getCookies();
      String cookieString = "";
      
      for (Cookie cookie : cookies) {
          cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
      }
      
      httpURLConnection.addRequestProperty("Cookie", cookieString);
      

      然后您可以使用HttpURLConnection.getInputStream() 将文件内容写入您的首选位置。

      try (InputStream in = httpURLConnection.getInputStream()) {
          Files.copy(in, new File("/path/to/file.ext").toPath(),
              StandardCopyOption.REPLACE_EXISTING);
      }
      

      虽然这种方法对于不同的编程语言会有所不同,但对所有浏览器都一样

      【讨论】:

        【解决方案4】:
        String path="D:\xyz\abc\";
        
        FirefoxOptions profile = new FirefoxOptions();
        
        profile.addPreference("browser.download.folderList", 2);
        
        profile.addPreference("browser.download.manager.showWhenStarting", false);
        
        profile.addPreference("browser.download.dir", **path**);
        
        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");
        
        profile.addPreference("browser.helperApps.alwaysAsk.force", false);
        
        profile.addPreference("browser.download.manager.alertOnEXEOpen", false);
        
        profile.addPreference("browser.download.manager.focusWhenStarting", false);
        
        profile.addPreference("browser.download.manager.useWindow", false);
        
        profile.addPreference("browser.download.manager.showAlertOnComplete", false);
        
        profile.addPreference("browser.download.manager.closeWhenDone", false);
        
        new FirefoxDriver(profile);
        

        【讨论】:

          【解决方案5】:

          可能会出现取消/保存对话框弹出窗口,因为该网站正在向您发送不同的 MIME 类型。

          检查实际的标题内容。

          使用开发人员工具中内置的 Firefox,右键单击以检查您发布的元素/下载链接,然后查看网络监视器以查看返回的 ContentType 标头值。这将是您要使用的那个。

          相应地设置您的个人资料设置

           firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                               "application/octet-stream,text/csv");
          

          我期待“text/csv”,但得到了“application/octet-stream” 一旦将其添加到接受的类型列表中,它就会按预期工作,没有弹出窗口

          【讨论】:

          • 哇,感谢您强调必须真正检查实际标题内容这一事实。由于我正在下载的文件是 csv,我认为它应该是 text/csv 但我错了。在我的情况下,它甚至不像你的情况那样application/octet-stream,而是application/csv。谢谢!
          【解决方案6】:

          我认为您正在寻找类似的东西

          //common to all the cases
          FirefoxProfile prof = new FirefoxProfile();
          
          //Case:1 - Use this case to set download this code to your browser's default location
          //prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
          
          //Case:2 - Download file to Desktop
          //prof.setPreference("browser.download.folderList", 0);
          //prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
          
          //Case:3 - Download to custom folder path. Replace d:\\selenium with your Download Location 
          prof.setPreference("browser.download.dir","D:\\selenium\\");
          prof.setPreference("browser.download.folderList", 2);
          prof.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/zip");
          
          //This will work for all cases mentioned above
          WebDriver driver = new FirefoxDriver(prof);
          driver.get("http://docs.seleniumhq.org/download/");
          driver.findElement(By.xpath("//tr[1]/td[4]/a[text()='Download']")).click();
          

          【讨论】:

          • 我在 Ubuntu 上试过这个,但是为什么所有文件都存储到 /tmp/mozilla_[user]0/ 文件以 .part 结尾
          【解决方案7】:

          您将无法访问保存对话框。这是由操作系统控制的。您真正能够做的唯一一件事就是为浏览器设置默认下载位置并允许它自动下载文件。然后在 Java 中检查文件。

          您应该从this previous SO question 检查this answer。基本上,在设置您的 Firefox 配置文件时,您添加一个调用以将属性 browser.helperApps.neverAsk.saveToDisk 设置为一个逗号分隔的 MIME 类型列表以始终下载:

          firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
          

          在 About:configs 上查看 this Mozilla KB FAQ article

          更新 看起来这现在可能see this answer in another question

          【讨论】:

          • 可以访问保存对话框,您可以使用机器人类来访问和执行使用机器人类的 ENTER、TABS 和 ESCAPE 等事件
          • @Luffy,谢谢。我看到您在另一个问题中发布了答案。当我第一次回答这个问题时,这是不可能的。我已更新答案以参考您的解决方案。
          • 我不明白,我使用了这些确切的设置并且pdf正常打开,它不保存到磁盘。除了使用请求之外还有其他选择吗,毕竟这将是一个糟糕的解决方法......(有关pdf页面的信息将其设置为“应用程序/pdf”,所以看起来还可以)?谢谢
          • 如果我还不知道下载文件的类型怎么办?它可以是动态的吗?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-15
          • 2019-12-26
          • 1970-01-01
          • 1970-01-01
          • 2012-06-03
          • 2016-08-18
          • 1970-01-01
          相关资源
          最近更新 更多