2016-11-23 127 views
2

我想使用Selenium WebDriver自動化文件下載功能。我使用Google Chrome,並且要下載的文件類型爲PDF格式。當WebDriver點擊下載(或打印)鏈接時,瀏覽器顯示PDF文件的預覽,而不是直接下載。我如何使鉻驅動程序直接下載PDF文件? 我嘗試下面的代碼,但沒有運氣使用chromedriver直接下載PDF文件

ChromeOptions options = new ChromeOptions(); 
Map<String,Object> preferences = new HashMap<>(); 
preferences.put("pdfjs.disabled", true); 
options.setExperimentalOption("prefs", preferences); 
System.setProperty("webdriver.chrome.driver", chromeDriverPath); 
WebDriver driver=new ChromeDriver(options); 

我知道這個問題已經問在計算器上,包括this,但這些解決方案都爲我工作。

我使用 - 谷歌瀏覽器v54.0.2840.99,Chromedriver和V2.25硒V3.0.1

下載/打印鏈接的HTML如下所示

enter image description here

+0

做你能顯示應用程序的HTML或URL? – Buaban

回答

2

這個問題可以通過將以下屬性添加到下載/打印元素

download="" 
target="_blank" 

來解決這可以使用JavaScript如下

WebElement printLink=driver.findElements(By.linkText("Print")).get(0); 
JavascriptExecutor js= (JavascriptExecutor) driver; 
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",printLink,"download",""); 
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",printLink,"target","_blank"); 
2

你可以設置a元素的屬性download,然後單擊該元素。請參見下面的代碼:

String script = "document.querySelector('td a[href*=\"/print/\"]').setAttribute('download','name-of-the-download-file-recommend-guid-or-timestamp.pdf');"; 
((JavascriptExecutor)driver).executeScript(script); 
driver.findElement(By.cssSelector("td a[href*='/print/']")).click(); 
+0

其實這個解決方案對我不起作用,但它給了我一些想法如何解決問題 – stackoverflow