我正在研究别人的代码,应该使用硒自动从网页上下载PDF文件,
我一直收到firefox下载确认提示,即使在browser.helperApps.neverAsk.saveToDisk属性中也包含PDF mime类型。
我正在使用Selenium 3.12.0,我将firefox版本从70降级到60.0,但都没有用。我不确定是代码问题还是Selenium firefox兼容问题。
感谢您的帮助。
编辑:这是向下贷款确认弹出窗口的样子。
private static final String mimeTypeToSaveToDisk = "application/pdf;application/zip";
public void download(String url,String downloadDirPath) {
// FirefoxProfile
FirefoxProfile profile = new FirefoxProfile();
profile.setacceptUntrustedCertificates(true);
profile.setassumeUntrustedCertificateIssuer(false);
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.dir",downloadDirPath);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",mimeTypeToSaveToDisk);
profile.setPreference("browser.helperApps.alwaysAsk.force",false);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.manager.closeWhenDone",true);
// FirefoxOptions
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability(FirefoxDriver.PROFILE,profile);
firefoxOptions.setCapability(CapabilityType.accEPT_SSL_CERTS,true);
// firefoxOptions.setBinary("C:/PathTo/firefox.exe");
// Proxy
if(!StringUtil.isnullOrEmpty(EmailProperties.getProxyHost(null))){
String Proxy_URL = EmailProperties.getProxyHost(null)+":"+ EmailProperties.getProxyPort(null);
Proxy Proxy = new Proxy();
Proxy.setHttpProxy(Proxy_URL).setftpProxy(Proxy_URL).setSslProxy(Proxy_URL);
firefoxOptions.setCapability(CapabilityType.Proxy,Proxy);
}
WebDriver driver = new FirefoxDriver(firefoxOptions);
driver.get(url);
ExpectedCondition<Boolean> expectedCondition = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
}
};
try {
Thread.sleep(timeSleep * 1000);
WebDriverWait wait = new WebDriverWait(driver,timeOut);
wait.until(expectedCondition);
} catch (Throwable e) {
logger.error("Timeout waiting for Page Load Request to complete.",e);
}
By by = By.xpath("//a[starts-with(@id,'file_')]");
List<WebElement> elements = driver.findElements(by);
for (int Counter = 0; Counter < elements.size(); Counter++) {
elements.get(Counter).click();
}
try {
File downloadFile [] = null;
int nbSleep = 0;
while(nbSleep <= 10 && (downloadFile == null || downloadFile.length>0)){
logger.debug("Téléchargement ZIP non finalisé,on attend "+((nbSleep+1)*timeSleep * 1000)+" secondes ...");
Thread.sleep(timeSleep * 1000);
nbSleep++;
downloadFile = new File(downloadDirPath).listFiles(
new FilenameFilter(){
@Override
public boolean accept(File dir,String name) {
return name.endsWith(".part");
}
}
);
}
if(downloadFile == null || downloadFile.length>0){
logger.error("Téléchargement ZIP non finalisé après attente de "+((nbSleep+1)*timeSleep * 1000)+" secondes ...");
}
} catch (Throwable e) {
logger.error("Timeout waiting for Page Load Request to complete.",e);
}
driver.quit();
}