设置Firefox配置文件以使用Selenium和Java自动下载文件

sta*_*low 19 java selenium-webdriver

我想使用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); 
Run Code Online (Sandbox Code Playgroud)

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

Flo*_* B. 37

就像@Jason建议的那样,它很可能是另一种mime类型.要获取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.helperApps.neverAsk.saveToDisk", "application/pdf");
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();
Run Code Online (Sandbox Code Playgroud)

  • `FirefoxDriver(profile)`现在被标记为已弃用.可以使用`FirefoxOptions options = new FirefoxOptions();``options.setProfile(profile);``WebDriver driver = new FirefoxDriver(options);` (4认同)
  • 我必须使用此答案中列出的所有选项,再加上一个:`profile.setPreference("browser.download.useDownloadDir", true);` (2认同)
  • 从 Firefox 81 开始,您还必须清除首选项 browser.download.viewableInternally.enabledTypes。否则,如果没有用户交互,则不会下载该列表中的文件类型。 (2认同)

7ca*_*ect 7

它目前在 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);
Run Code Online (Sandbox Code Playgroud)

每个Firefox 配置文件设置的详细信息