如何使用selenium webdriver在chrome中下载pdf文件
我想使用selenium在chrome中下载pdf。
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + System.getProperty("file.separator") + "BrowserDrivers" + System.getProperty("file.separator") + "chromedriver.exe"); String downloadFilepath = "C:\\Users\\Vinod\\Downloads"; HashMap chromePrefs = new HashMap(); chromePrefs.put("profile.default_content_settings.popups", 0); chromePrefs.put("download.default_directory", downloadFilepath); //Save Chrome Opions ChromeOptions options = new ChromeOptions(); HashMap chromeOptionsMap = new HashMap(); options.setExperimentalOption("prefs", chromePrefs); options.addArguments("--test-type"); DesiredCapabilities cap = DesiredCapabilities.chrome(); cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap); cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); cap.setCapability(ChromeOptions.CAPABILITY, options); driver = new ChromeDriver(cap); driver.get(url);
我尝试了上面的代码,但它不起作用
您可以加载此页面并使用selenium导航更改设置:
chrome://settings/content/pdfDocuments
由于chrome 57自动pdf预览不再作为插件工作,现在有一个设置可以更改以使其工作。 实际上,您可以通过检查chrome自己的首选项对话框来检查pref的名称,在“内容设置”下,标记为“在默认PDF查看器应用程序中打开PDF文件”。
您可以将其设置为false以避免自动pdf预览,如下所示(ruby示例):
caps = Selenium::WebDriver::Remote::Capabilities.chrome( "chromeOptions" => { 'args' => ['disable-gpu', "--window-size=1920,1080"], prefs: { "download.prompt_for_download": false, "download.directory_upgrade": true, "plugins.always_open_pdf_externally": true, "download.default_directory": DownloadHelpers::PATH.to_s } } ) Capybara::Selenium::Driver.new( app, browser: :chrome, desired_capabilities: caps )
您需要在Chrome配置文件中添加以下语句:
chromePrefs.put("pdfjs.disabled", true);
似乎新版本的浏览器具有在浏览器中显示PDF文件的内置function。 请参阅此内容以获取更多信息,虽然它适用于Firefox的配置文件,但仍然可以很好地阅读。
希望能解决您的问题,否则您可能需要降级您的chrome以使其正常工作。 如果您有任何疑问,请告诉我。
您使用Adobe Acrobat / Adobe Reader显示PDF吗? 如果是这样,那么您可能需要修改Abode的行为。
以下是我必须采取的步骤:
- 打开Adobe Reader
- 编辑菜单,首选项
- 从类别列表中选择Selcet Internet
- 取消选中在浏览器中显示PDF
- 按确定
您还可以在Chrome中停用Adobe插件,这会迫使Chrome下载PDF。
它位于chrome:// plugins下。
但正如你所说的最新的Chrome浏览器然后检查是否在插件中可见的chrome PDF视图,如果是也禁用它。
- 禁用“Chrome PDF Viewer”或取消标记始终允许运行复选框同时尝试两者