下面的代码中,我尝试使用无头模式下的硒从chrome浏览器下载PDF。对于PDF文件,它工作正常,但对于.cfm
文件而言,效果很好。
public static void main(String args[]) throws InterruptedException, AWTException, IOException, DocumentException {
System.setProperty("webdriver.chrome.driver", "/home/OtherProj/webDrivers/chromedriver_64");
String downloadPath = "/home/Downloads/AAAA/";
File file = new File(downloadPath);
if(!file.exists())
file.mkdirs();
ChromeOptions chromeOptions = new ChromeOptions();
HashMap<String, Object> prefs = new HashMap<>();
prefs.put("plugins.always_open_pdf_externally", true);
chromeOptions.addArguments("--test-type");
chromeOptions.addArguments("--disable-extensions");
chromeOptions.setExperimentalOption("prefs", prefs);
chromeOptions.setHeadless(true);
String pdfUrl = "https://www.dummyurl.com/prod/formPDF.cfm";
ChromeDriverService driverService = ChromeDriverService.createDefaultService();
WebDriver driver = new ChromeDriver(driverService, chromeOptions);
// Saves the file on the given path
PDFDemo.downloadFile(downloadPath, driverService, driver, pdfUrl);
System.out.println("Document Downloaded..");
}
private static void downloadFile(String downloadPath, ChromeDriverService driverService, WebDriver driver, String pdfUrl) throws ClientProtocolException, IOException, InterruptedException {
Map<String, Object> commandParams = new HashMap<>();
commandParams.put("cmd", "Page.setDownloadBehavior");
Map<String, String> params = new HashMap<>();
params.put("behavior", "allow");
params.put("downloadPath", downloadPath);
commandParams.put("params", params);
HttpClient httpClient = HttpClientBuilder.create().build();
ObjectMapper objectMapper = new ObjectMapper();
String command = objectMapper.writeValueAsString(commandParams);
String u = driverService.getUrl().toString() + "/session/" + ((RemoteWebDriver) driver).getSessionId() + "/chromium/send_command";
HttpPost request = new HttpPost(u);
request.addHeader("content-type", "text/x-cfm");
request.setEntity(new StringEntity(command));
httpClient.execute(request);
// Opens pdf of specific URL
driver.get(pdfUrl);
}
我还参考了以下答案,但没有用。另外我在控制台上也没有任何异常。
Download files in Java, Selenium using ChromeDriver and headless mode