如何使用Selenium Webdriver下载任何文件并将其保存到所需位置

时间:2023-02-06 00:29:06

I have to perform following task using Selenium Webdriver given below.

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

  1. Click on any link/button that start downloading any file (filetype may be anything image, pdf, jar etc)
  2. 点击开始下载任何文件的任何链接/按钮(文件类型可能是任何图像,pdf,jar等)
  3. Click on the "Save" on popup if appeared (e.g. in case of http://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar)
  4. 如果出现,请点击弹出窗口中的“保存”(例如http://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar)
  5. Give the desired location to save that file.
  6. 提供所需的位置以保存该文件。

Can anyone share, how can we implement this using Java?

任何人都可以共享,我们如何使用Java实现这一点?

7 个解决方案

#1


21  

You won't be able to access the save dialog box. That's controlled by the OS. The only thing you're really going to be able to do is set the default download location for the browser and allow it to automatically download the files. Then check the file in Java.

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

You should check this answer from this previous SO question. Basically when setting up your Firefox profile you add a call to set the property browser.helperApps.neverAsk.saveToDisk to a comma separated list of MIME types to always download:

您应该从之前的SO问题中查看此答案。基本上,在设置Firefox配置文件时,添加一个调用以将属性browser.helperApps.neverAsk.saveToDisk设置为以逗号分隔的MIME类型列表,以便始终下载:

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

See this Mozilla KB FAQ article on About:configs.

请参阅关于:configs的Mozilla KB FAQ文章。

UPDATE It looks like this may now be possible see this answer in another question

更新看起来这可能现在可以在另一个问题中看到这个答案

#2


7  

The Cancel/Save dialogue popup may be appearing because the site is sending you a different MIME type.

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

Check the actual header content.

检查实际的标题内容。

Using the firefox built in Developer tools, Right click to inspect the element/download link your posting then take a look at the Network monitor to see the ContentType header value returned.. That would be the one you want to use..

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

如何使用Selenium Webdriver下载任何文件并将其保存到所需位置

Set your profile settings accordingly

相应地设置配置文件设置

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

I was expecting "text/csv" however got "application/octet-stream" once that was added to the accepted types list it all worked as expected, No popups

我期待“text / csv”然而得到“application / octet-stream”一旦被添加到接受的类型列表中它都按预期工作,没有弹出窗口

#3


2  

One potential solution is to obtain the URL for the file via Selenium, create a (non-Selenium) connection, copy Selenium's cookies to the connection (if necessary), and download the file. Most languages have APIs (or libraries) for performing HTTP requests. For example, to accomplish this in Java, you could use URL.openConnection():

一种可能的解决方案是通过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");

You may need to copy over the cookies that Selenium has in order to imitate the Selenium user (for example if you are testing a website that requires a sign-in).

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

Set<Cookie> cookies = webDriver.manager().getCookies();
String cookieString = "";

for (Cookie cookie : cookies) {
    cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}

httpURLConnection.addRequestProperty("Cookie", cookieString);

Then you can use HttpURLConnection.getInputStream() to write the file contents to your preferred location.

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

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

Although, this method would be different for different programming languages, it works the same for all browsers.

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

#4


1  

I think you are looking for something like this

我想你正在寻找这样的东西

//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();

#5


0  

In case you are using Java and Chromdriver, I developed a library which should make your downloads much easier.

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

Among its features, you can set your download directory in one code line and verify that your file was downloaded successfully:

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

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

#6


0  

You can use the below code to save the file to the required location.

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

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();
    }

}

#7


-2  

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);

#1


21  

You won't be able to access the save dialog box. That's controlled by the OS. The only thing you're really going to be able to do is set the default download location for the browser and allow it to automatically download the files. Then check the file in Java.

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

You should check this answer from this previous SO question. Basically when setting up your Firefox profile you add a call to set the property browser.helperApps.neverAsk.saveToDisk to a comma separated list of MIME types to always download:

您应该从之前的SO问题中查看此答案。基本上,在设置Firefox配置文件时,添加一个调用以将属性browser.helperApps.neverAsk.saveToDisk设置为以逗号分隔的MIME类型列表,以便始终下载:

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

See this Mozilla KB FAQ article on About:configs.

请参阅关于:configs的Mozilla KB FAQ文章。

UPDATE It looks like this may now be possible see this answer in another question

更新看起来这可能现在可以在另一个问题中看到这个答案

#2


7  

The Cancel/Save dialogue popup may be appearing because the site is sending you a different MIME type.

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

Check the actual header content.

检查实际的标题内容。

Using the firefox built in Developer tools, Right click to inspect the element/download link your posting then take a look at the Network monitor to see the ContentType header value returned.. That would be the one you want to use..

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

如何使用Selenium Webdriver下载任何文件并将其保存到所需位置

Set your profile settings accordingly

相应地设置配置文件设置

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

I was expecting "text/csv" however got "application/octet-stream" once that was added to the accepted types list it all worked as expected, No popups

我期待“text / csv”然而得到“application / octet-stream”一旦被添加到接受的类型列表中它都按预期工作,没有弹出窗口

#3


2  

One potential solution is to obtain the URL for the file via Selenium, create a (non-Selenium) connection, copy Selenium's cookies to the connection (if necessary), and download the file. Most languages have APIs (or libraries) for performing HTTP requests. For example, to accomplish this in Java, you could use URL.openConnection():

一种可能的解决方案是通过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");

You may need to copy over the cookies that Selenium has in order to imitate the Selenium user (for example if you are testing a website that requires a sign-in).

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

Set<Cookie> cookies = webDriver.manager().getCookies();
String cookieString = "";

for (Cookie cookie : cookies) {
    cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}

httpURLConnection.addRequestProperty("Cookie", cookieString);

Then you can use HttpURLConnection.getInputStream() to write the file contents to your preferred location.

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

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

Although, this method would be different for different programming languages, it works the same for all browsers.

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

#4


1  

I think you are looking for something like this

我想你正在寻找这样的东西

//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();

#5


0  

In case you are using Java and Chromdriver, I developed a library which should make your downloads much easier.

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

Among its features, you can set your download directory in one code line and verify that your file was downloaded successfully:

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

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

#6


0  

You can use the below code to save the file to the required location.

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

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();
    }

}

#7


-2  

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);