问题描述
我想使用 Selenium WebDriver 和 Java 验证文件下载.要下载的文件为 PDF 格式.当 WebDriver 单击 AUT 中的下载"链接时,Firefox 会打开以下下载确认窗口:
I want to verify file download using Selenium WebDriver and Java. The file to download is of PDF format. When WebDriver clicks on "Download" link in the AUT, Firefox opens up the following download confirmation window:
我想让 Firefox 自动下载文件而不显示上面的确认窗口,所以我使用了下面的代码:
I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:
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 文件?
but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?
推荐答案
就像@Jason 建议的那样,它很可能是另一种 mime 类型.获取 mime 类型:
Just like @Jason suggested, it's most probably another mime type.To get the mime type:
- 打开开发者工具
- 转到网络
- 点击链接下载pdf
- 在网络面板中,选择第一个请求
- MIME 类型是响应标头中的 Content-Type:
然后使用 Firefox 下载 PDF:
Then to download a PDF with Firefox:
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();
这篇关于将 Firefox 配置文件设置为使用 Selenium 和 Java 自动下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!