【问题标题】:Set Firefox profile to download files automatically using Selenium and Java将 Firefox 配置文件设置为使用 Selenium 和 Java 自动下载文件
【发布时间】:2016-07-18 11:38:29
【问题描述】:

我想使用 Selenium WebDriver 和 Java 验证文件下载。下载的文件为PDF格式。当 WebDriver 点击 AUT 中的“下载”链接时,Firefox 会打开以下下载确认窗口:

我希望 Firefox 自动下载文件而不显示上面的确认窗口,所以我使用了以下代码:

FirefoxProfile firefoxProfile=new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir",downloadPath);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf");
WebDriver driver=new FirefoxDriver(firefoxProfile); 

但 Firefox 仍然显示相同的窗口。如何设置 Firefox 配置文件,以便在不显示确认对话框的情况下自动下载 PDF 文件?

【问题讨论】:

  • 回复的mime-type 是什么?试试看:firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf,application/x-pdf,application/octet-stream");
  • JRodDynamite 是正确的,你需要把它们都放在一行,否则只会取最后一行。

标签: java selenium-webdriver


【解决方案1】:

就像@Jason 建议的那样,它很可能是另一种哑剧类型。 要获取 mime 类型:

  • 打开开发者工具
  • 转到网络
  • 点击链接下载pdf
  • 在网络面板中,选择第一个请求
  • mime 类型是响应标头中的 Content-Type:

然后用 Firefox 下载 PDF:

FirefoxOptions options = new FirefoxOptions();
options.setPreference("browser.download.folderList", 2);
options.setPreference("browser.download.dir", "C:\\Windows\\temp");
options.setPreference("browser.download.useDownloadDir", true);
options.setPreference("browser.download.viewableInternally.enabledTypes", "");
options.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf;text/plain;application/text;text/xml;application/xml");
options.setPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer

WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.mozilla.org/en-US/foundation/documents");
driver.findElement(By.linkText("IRS Form 872-C")).click();

【讨论】:

  • mime 类型为 application/pdf。我可以在开发人员选项卡控制台中看到一条消息“资源解释为文档但使用 MIME 类型应用程序/pdf 传输”。这条消息是否与@Jason 的问题有任何关系
  • 我用禁用内置查看器的示例更新了答案。让我知道它是否适合您。
  • 我必须使用此答案中列出的所有选项,再加上一个:profile.setPreference("browser.download.useDownloadDir", true);
  • FirefoxDriver(profile) 现在被标记为已弃用。可以改用FirefoxOptions options = new FirefoxOptions();options.setProfile(profile);WebDriver driver = new FirefoxDriver(options);
  • 从 Firefox 81 开始,您还必须清除首选项 browser.download.viewableInternally.enabledTypes。否则,如果没有用户交互,则不会下载该列表中的文件类型。
【解决方案2】:

它目前在 Firefox 57.0b13 中的工作方式是

FirefoxProfile profile = new FirefoxProfile();
// profile.setPreference("browser.download.useDownloadDir", true); This is true by default. Add it if it's not working without it.

profile.setPreference("browser.download.folderList",2); //Use for the default download directory the last folder specified for a download
profile.setPreference("browser.download.dir", "/Path/to/directory"); //Set the last directory used for saving a file from the "What should (browser) do with this file?" dialog.
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf"); //list of MIME types to save to disk without asking what to use to open the file
profile.setPreference("pdfjs.disabled", true);  // disable the built-in PDF viewer

firefoxOptions.setProfile(profile);

每个Firefox profile setting的详细信息

【讨论】:

    【解决方案3】:

    如果有人在 SPA 环境中遇到此问题,那么我遇到了一个问题,即将 saveToDisk 首选项设置为预期的内容类型不起作用(在我的情况下为 text/csv)。

    原因是 SPA UI 向后端 api 发起 HTTP 调用以获取 CSV 数据。然后它会创建一个<A> 元素,单击该元素以启动到本地计算机的下载。该技巧使用 CSV 数据创建一个 Blob 对象,并且类型必须设置为 application/octet-stream 作为其中的一部分。因此,saveToDisk 也必须设置为 application/octet-stream 才能正常工作。

    【讨论】:

    • 我确定你的意思是 application/octet-stream 不是 octet/stream
    【解决方案4】:

    现在是 2020 年。找到上面提到的@Florent B. 的 MIME 类型。 对我来说,下载 csv 文件,发现 Content-Type = "application/octet-stream"

    下载到文件夹下载:

    FirefoxOptions options = new FirefoxOptions();
    options.addPreference("browser.download.folderList",1);
    options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");
    WebDriver driver = new FirefoxDriver(options);
    

    要下载到桌面,请将第 2 行的值更改为 0:

    FirefoxOptions options = new FirefoxOptions();
    options.addPreference("browser.download.folderList",0);
    options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");
    WebDriver driver = new FirefoxDriver(options);
    

    要下载到另一个文件夹:

    FirefoxOptions options = new FirefoxOptions();
    options.addPreference("browser.download.dir", "D:\\Test");
    options.addPreference("browser.download.folderList",2);
    options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream");
    WebDriver driver = new FirefoxDriver(options);
    

    【讨论】:

      【解决方案5】:

      我会写这个作为评论,但我没有足够的声誉点——一旦 selenium webdriver 启动,你可以导航到 about:config 并搜索 browser.helperApps.neverAsk.saveToDisk 以确认您指定的类型已正确记录。

      在我的情况下,问题也解决了,包括

      prof.set_preference("browser.helperApps.neverAsk.openFile", "application/pdf, application/octet-stream, application/x-winzip, application/x-pdf, application/x-gzip")
      

      【讨论】:

        【解决方案6】:

        如果您像我一样,正在查看其他文件类型或多种类型。确保只设置一次 neverAsk 首选项。

        opts.set_preference('browser.download.folderList', 2)
        opts.set_preference('browser.download.manager.showWhenStarting', False)   opts.set_preference('browser.download.dir', str(download_directory))    opts.set_preference('browser.download.useDownloadDir', True)
        
        # important part!
        opts.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip')
        

        如果人们知道如何包含多个 mime 类型,我会很乐意更新此内容!

        其他 mime 类型供快速参考:

        # CSV mimetype = 'text/csv'
        # TXT mimetype = 'text/txt'
        # EXCEL mimetype = 'application/vnd.ms-excel'
        

        【讨论】:

        • 这是/曾经是我的答案。 “从不询问”偏好一次。如果我能把那几个小时倒过来。
        【解决方案7】:

        呃,根据 JRodDynamite 的回答:

        opts.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip,text/csv,text/txt')
        

        应该为多种 mime 类型解决问题 - 在这种情况下,仅适用于 zip、csv 和 txt 文件。

        就个人而言,(以及我现在出现在此页面上的原因)我发现“只需保存 #$&*!”这句话令人费解。选项不是“未知”(又名“应用程序/八位字节流”)文件类型的默认选项。 哦,好吧,这就是生活! :)

        【讨论】:

          【解决方案8】:
              WebDriver driver;
          //For firefox
              FirefoxOptions options = new FirefoxOptions(); //For setting up options for Firefox
              DesiredCapabilities firefoxDesiredCapabilities = new DesiredCapabilities(); //Initializing desired capabilities
              options.addPreference("browser.download.folderList", 2); //Last downloaded folder
              options.addPreference("browser.download.dir", "[path]"); // Set your default download directory's path
              options.addPreference("browser.privatebrowsing.autostart", true); 
              options.addPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain; charset=utf-8; text/csv;application/json;charset=utf-8;application/pdf;text/plain;application/text;text/xml;application/xml"); //includes a varied list of context-type but feel free to add others
              options.addPreference("pdfjs.disabled", true);
              options.addArguments("-private");//for incognito
              firefoxDesiredCapabilities.setCapability("moz:firefoxOptions",options); //Load all options to desired capabilities
              driver = new FirefoxDriver(firefoxDesiredCapabilities); //launch your driver using desiredcapalities
          

          //对于 Chrome

          ChromeOptions options = new ChromeOptions();
          Map<String, Object> prefs = new HashMap<String, Object>();
          prefs.put("profile.default_content_settings.popups", 0);//Don't display any popup for download
          prefs.put("download.default_directory", "[path]");//Default download directory
          options.setExperimentalOption("prefs", prefs);
          options.addArguments("--incognito");
          DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
          desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
          desiredCapabilities.setCapability("applicationCacheEnabled", false);
          driver = new ChromeDriver(desiredCapabilities);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-08-28
            • 2016-03-27
            • 1970-01-01
            • 2016-09-11
            • 2017-07-01
            • 2015-04-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多