设置Firefox配置文件以使用Selenium和Java自动下载文件
我想使用Selenium webdriver和Javavalidation文件下载。 要下载的文件是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文件而不显示确认对话框?
就像@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();
它目前在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配置文件设置的详细信息