有没有办法等待下载在WebDriver中完成?
基本上,我想验证下载的文件是否正确存储在硬盘驱动器内并验证,需要等到下载完成。如果有人事先知道这种情况,请提供帮助。
答案 0 :(得分:0)
不是您问题的直接答案,但我希望它会有所帮助。
将文件存储在硬盘驱动器上(计算其MD5)。一旦它是正确的,你可以进一步测试。如果超时后文件不正确,则会失败。
答案 1 :(得分:0)
轮询配置的下载目录以查找缺少部分文件。
以下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());
答案 2 :(得分:0)
正如Wait for Download to finish in 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;
}
然后您可以使用像this这样的库来进行实际的文件处理,以查看文件是否正确存储(这可能意味着比较文件大小,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"));
}
答案 3 :(得分:-1)
对于小文件,我目前要么使用隐含等待,要么等待我的文件已经下载的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)上测试这个