java - 将 Firefox 配置文件设置为使用 Selenium 和 Java 自动下载文件

标签 java selenium-webdriver

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

Download Confirmation Window

我希望 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 文件?

最佳答案

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

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

enter image description here

然后用 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();

关于java - 将 Firefox 配置文件设置为使用 Selenium 和 Java 自动下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309314/

相关文章:

java - 将 lambda 分配给功能接口(interface)变量 : inherited abstract method must be implemented. 时出错,为什么?

java - 使用字符串实现时,合并排序会生成任意顺序

java - 用显式等待替换隐式等待(selenium webdriver 和 java)

javascript - 尝试截屏时出现 WebDriverException

java - 如何在 Android 中使用 XPath 编辑属性

java - 错误意外 token '%' : JPQL - LIKE %FUNCTION(:namedParam)%

java - 在 Java 中使用 Selenium 2 将鼠标悬停在 WebElement 上

selenium - WebDriverIO : Starting Chrome with browser sessions & cookies

java - 每个集群中运行的监听器仅从主题消费一次消息

c# - 找不到按钮元素C#