繁体   English   中英

如何使用 Webdriver 等待下载完成

[英]How to wait for download to finish using Webdriver

有没有办法在 WebDriver 中等待下载完成?

基本上,我想验证下载的文件是否正确存储在硬盘驱动器中,并验证这一点,需要等到下载完成。 如果有人更早知道这种情况,请提供帮助。

不是直接回答您的问题,但我希望它会有所帮助。

将文件放在硬盘上(计算它的 MD5)。 一旦正确,您就可以进一步进行测试。 如果超时后文件不正确,则使 tets 失败。

轮询配置的下载目录是否缺少部分文件。

以下 Chrome 的示例代码:

    File destinationDir = new File("blah");

    Map<String, Object> prefs = new HashMap<>();
    prefs.put("download.default_directory", destinationDir.getAbsolutePath());

    DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();

    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", prefs);
    desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);

    WebDriver webDriver = new ChromeDriver(desiredCapabilities);
    // Initiate download...

    do {
        Thread.sleep(5000L);
    } while(!org.apache.commons.io.FileUtils.listFiles(destinationDir, new String[]{"crdownload"}, false).isEmpty());

正如在 Selenium webdriver JAVA 中等待下载完成所回答的那样

  private void waitForFileDownload(int totalTimeoutInMillis, String expectedFileName) throws IOException {  
            FluentWait<WebDriver> wait = new FluentWait(this.funcDriver.driver)
                                   .withTimeout(totalTimeoutInMillis, TimeUnit.MILLISECONDS)
                                   .pollingEvery(200, TimeUnit.MILLISECONDS);
            File fileToCheck = getDownloadsDirectory()
                               .resolve(expectedFileName)
                               .toFile();

            wait.until((WebDriver wd) -> fileToCheck.exists());

        }


public synchronized Path getDownloadsDirectory(){
        if(downloadsDirectory == null){

            try {
                downloadsDirectory = Files.createTempDirectory("selleniumdownloads_");
            } catch (IOException ex) {
                throw new RuntimeException("Failed to create temporary downloads directory");
            }
        }
        return downloadsDirectory;
    }

然后你可以使用库像这样做实际的文件处理看到的是正确地存储(这可能意味着比较文件的大小,MD5哈希值,甚至检查文件的内容,其蒂卡其实可以做的一样好)的文件。

public void fileChecker(){
        waitForFileDownload(20000,"filename_here");

        File file = downloadsDirectory.resolve(expectedFileName).toFile();

        AutoDetectParser parser = new AutoDetectParser();
        parser.setParsers(new HashMap<MediaType, Parser>());

        Metadata metadata = new Metadata();
        metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());

        try (InputStream stream = new FileInputStream(file)) {
            parser.parse(stream, (ContentHandler) new DefaultHandler(), metadata, new ParseContext());
        }

        String actualHash = metadata.get(HttpHeaders.CONTENT_MD5); 
        assertTrue("There was a hash mismatch for file xyz:",actualHash.equals("expectedHash"));
    }

我是你在 Python + Firefox 中的波纹管代码:

browser.get('about:downloads')  #Open the download page.
# WAit all icons change from "X" (cancel download).
WebDriverWait(browser, URL_LOAD_TIMEOUT * 40).until_not(
    EC.presence_of_element_located((By.CLASS_NAME, 'downloadIconCancel')))

对于小文件,我目前要么使用隐式等待,要么在继续之前等待我的文件下载的 JS 回调。 下面的代码是由另一个人在 SO 上发布的,我无法立即找到该帖子,因此我不会因此而受到赞扬。

public static void WaitForPageToLoad(IWebDriver driver) { TimeSpan timeout = new TimeSpan(0, 0, 2400); WebDriverWait wait = new WebDriverWait(driver, timeout);

        IJavaScriptExecutor javascript = driver as IJavaScriptExecutor;
        if (javascript == null)
            throw new ArgumentException("driver", "Driver must support javascript execution");

        wait.Until((d) =>
        {
            try
            {
                string readyState = javascript.ExecuteScript("if (document.readyState) return document.readyState;").ToString();
                return readyState.ToLower() == "complete";
            }
            catch (InvalidOperationException e)
            {
                //Window is no longer available
                return e.Message.ToLower().Contains("unable to get browser");
            }
            catch (WebDriverException e)
            {
                //Browser is no longer available
                return e.Message.ToLower().Contains("unable to connect");
            }
            catch (Exception)
            {
                return false;
            }
        });
    }

如果文件很小,它应该等待您的文件完成。 不幸的是,我还没有在较大的文件(> 5MB)上测试过这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM