有什么方法可以等待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());
正如在 等待下载完成 在硒网络驱动程序 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哈希,甚至检查Tika实际上也可以执行的文件内容)。
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"));
}
<</div>
div class="one_answers">我是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) { 时间跨度超时 = 新的时间跨度(0, 0, 2400); WebDriverWait = 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)上对此进行测试