简体   繁体   English

如何使用 Webdriver 等待下载完成

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

Is there any way to wait for a download to finish in WebDriver?有没有办法在 WebDriver 中等待下载完成?

Basically, I want to verify that downloaded file getting stored correctly inside hard drive and to verify that, need to wait till download finishes.基本上,我想验证下载的文件是否正确存储在硬盘驱动器中,并验证这一点,需要等到下载完成。 Please help if anyone aware of such a scenario earlier.如果有人更早知道这种情况,请提供帮助。

Not a direct answer to your question but I hope it will help.不是直接回答您的问题,但我希望它会有所帮助。

Pool the file on your hard drive (compute a MD5 of it).将文件放在硬盘上(计算它的 MD5)。 Once it is correct, you can go further with your test.一旦正确,您就可以进一步进行测试。 Fail your tets if the file is not correct after a timeout.如果超时后文件不正确,则使 tets 失败。

Poll the configured download directory for absence of partial file.轮询配置的下载目录是否缺少部分文件。

Example code for Chrome below:以下 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());

As answered on Wait for Download to finish in selenium webdriver JAVA正如在 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;
    }

Then you can use a library like this to do the actual file handling to see the file is stored correctly (that could mean comparing file size, Md5 hashes or even checking the content of the file which Tika can actually do as well).然后你可以使用库像这样做实际的文件处理看到的是正确地存储(这可能意味着比较文件的大小,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"));
    }

I am your the bellow code in Python + Firefox:我是你在 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')))

For small files, I currently either use an implied wait or wait for the JS callback that my file has downloaded before moving on.对于小文件,我目前要么使用隐式等待,要么在继续之前等待我的文件下载的 JS 回调。 The code below was posted on SO by another individual, I can't find the post right away, so I won't take credit for it.下面的代码是由另一个人在 SO 上发布的,我无法立即找到该帖子,因此我不会因此而受到赞扬。

public static void WaitForPageToLoad(IWebDriver driver) { TimeSpan timeout = new TimeSpan(0, 0, 2400); public static void WaitForPageToLoad(IWebDriver driver) { TimeSpan timeout = new TimeSpan(0, 0, 2400); WebDriverWait wait = new WebDriverWait(driver, timeout); 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;
            }
        });
    }

It should wait for your file to finish if it is small.如果文件很小,它应该等待您的文件完成。 Unfortunately, I haven't tested this on larger files ( > 5MB )不幸的是,我还没有在较大的文件(> 5MB)上测试过这个

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

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