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

如何使用SeleniumWebDriver下载任何文件并将其保存到所需位置,selenium,selenium-webdriver,Selenium,Selenium Webdriver,我必须使用下面给出的SeleniumWebDriver执行以下任务 单击开始下载任何文件的任何链接/按钮(文件类型可以是任何图像、pdf、jar等) 如果出现弹出窗口,请单击“保存”(例如,在以下情况下) 指定保存该文件所需的位置 任何人都可以共享,我们如何使用Java实现这一点?您将无法访问“保存”对话框。这是由操作系统控制的。您真正能够做的唯一一件事就是为浏览器设置默认下载位置,并允许它自动下载文件。然后检查Java中的文件 你应该去检查一下。基本上,在设置Firefox配置文件时,您会添加

我必须使用下面给出的SeleniumWebDriver执行以下任务

  • 单击开始下载任何文件的任何链接/按钮(文件类型可以是任何图像、pdf、jar等)
  • 如果出现弹出窗口,请单击“保存”(例如,在以下情况下)
  • 指定保存该文件所需的位置

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

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

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

    firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
    
    请参见关于:配置

    更新
    现在看来这是可能的

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

    //所有案例都通用
    FirefoxProfile prof=新的FirefoxProfile();
    //案例:1-使用此案例将下载此代码设置为浏览器的默认位置
    //prof.setPreference(“browser.helperApps.neverAsk.saveToDisk”,“application/zip”);
    //案例:2-将文件下载到桌面
    //prof.setPreference(“browser.download.folderList”,0);
    //prof.setPreference(“browser.helperApps.neverAsk.saveToDisk”,“application/zip”);
    //案例:3-下载到自定义文件夹路径。将d:\\selenium替换为您的下载位置
    prof.setPreference(“browser.download.dir”,“D:\\selenium\\”;
    setPreference教授(“browser.download.folderList”,2);
    prof.setPreference(“browser.helperApps.neverAsk.saveToDisk”,“application/zip”);
    //这将适用于上述所有情况
    WebDriver=新的FirefoxDriver(prof);
    驱动程序。获取(“http://docs.seleniumhq.org/download/");
    findElement(By.xpath(“//tr[1]/td[4]/a[text()='Download'])。单击();
    
    可能会出现“取消/保存”对话框弹出窗口,因为网站正在向您发送不同的MIME类型

    检查实际标题内容。

    使用firefox内置的开发者工具,右键单击查看您发布的元素/下载链接,然后查看网络监视器以查看返回的ContentType标题值。。那就是你想用的

    相应地设置您的配置文件设置

     firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
                         "application/octet-stream,text/csv");
    
    我期待“text/csv”,但得到了“application/octet-stream”
    一旦它被添加到接受类型列表中,它就可以正常工作,没有弹出窗口

    一个潜在的解决方案是通过Selenium获取文件的URL,创建一个(非Selenium)连接,将Selenium的cookie复制到该连接中(如有必要),然后下载该文件。大多数语言都有用于执行HTTP请求的API(或库)。例如,要在Java中实现这一点,您可以使用:

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


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

    如果您使用的是Java和Chromdriver,我开发了一种可以让您的下载更容易的方法

    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);
    
    在其功能中,您可以在一个代码行中设置下载目录,并验证文件已成功下载:

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

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

    try (InputStream in = httpURLConnection.getInputStream()) {
        Files.copy(in, new File("/path/to/file.ext").toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }
    
    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();
        }
    
    }
    

    可以访问“保存”对话框,您可以使用robot类访问和执行事件,如使用robot进入、选项卡和转义class@Luffy谢谢我看到你在另一个问题中给出了答案。当我第一次回答这个问题时,这是不可能的。我已经更新了答案以引用您的解决方案。我不明白,我使用了这些精确的设置,pdf正常打开,它不会保存到磁盘。除了使用请求,还有其他选择吗?在所有这些工作之后,这将是一个糟糕的解决方法。。。(关于pdf页面的信息将其设置为“application/pdf”,这样看起来就可以了)?谢谢如果我还不知道下载文件的类型怎么办?它可以是动态的吗?哇,感谢你强调一个事实,那就是你必须真正检查实际的标题内容。因为我下载的文件是csv,我想应该是
    text/csv
    ,但我错了。在我的例子中,它甚至不像您的例子那样是
    application/octet-stream
    ,而是
    application/csv
    。谢谢您也可以使用AutoIT,在不更改或引用任何配置或属性文件的情况下,非常顺利地完成此操作。您可以在此处参考我对相关问题的回答:Sikulixapi将允许您访问对话框,并在要保存它的框中键入内容,同时按下保存按钮。我在Ubuntu上试过这个,但是为什么所有的文件都存储到/tmp/mozilla\u[user]0/中,文件以
    结尾
    
    @Test
    void downloadAttachTest() throws InterruptedException {
        adamInternetPage.navigateToPage(driver);
        seleniumDownloadKPI.fileDownloadKPI(
                adamInternetPage.getFileDownloadLink(), "SpeedTest_16MB.dat");
        waitBeforeClosingBrowser();
    }
    
    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();
        }
    
    }