首页 > 解决方案 > Selenium,无法自动下载文件,下载确认一直显示

问题描述

我正在研究其他人的代码,该代码应该使用 selenium 从网页自动下载 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();
}

标签: javascriptselenium

解决方案


我看到FirefoxOptions您正在使用,并想建议另一个尝试 -useDownloadDir选项。我知道您已经使用browser.download.dir,但这是一个不同的设置:

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);  // prevent PDF from opening after download

WebDriver driver = new FirefoxDriver(options);

推荐阅读