在关闭JAVA中的Selenium Web驱动程序之前,如何验证文件下载是否完成。
我已经编写了Selenium代码,可以将2个文件下载到所需的文件夹位置。但是,单击2个链接后,我立即关闭了浏览器,这使下载的文件成为临时文件或扩展名无效。在关闭Web驱动程序之前,单击两个链接中的每个链接后,我都使用了Thread.sleep方法,现在它可以正常工作。
我需要知道有没有一种最佳方法来检查下载是否已完成,然后使用显式方法或其他任何方法,而不是使用Thread.sleep()方法设置预定义时间来关闭Web驱动程序。
这里是与此问题相关的源代码(JAVA,Selenium和Testng)的一部分。
// Text file download
@Test(priority=2)
public void txtFileDownloadTest() {
fileDownloadPage.clickTxtFileLink();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Java file download
@Test(priority=3)
public void javaFileDownloadTest() {
fileDownloadPage.clickJavaFileLink();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterClass
public void setDown() {
closeUp();
}
我正在使用一段代码下载文件。只需更改fileName并增加waitSec(driver,int)的超时。
public WebDriverWait waitSec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
String fileName = "foo";
String filePathFull = "C:/users/user/downloads/" + fileName + ".csv";
waitSec(driver, 30).until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
if(Files.exists(Paths.get(filePathFull))) {
return true;
}
else {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
return false;
}
});
File exportFile = new File(filePathFull);
if (Files.size(Paths.get(filePathFull)) == 0) {
try {
waitSec(driver, 120).until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
try {
if(Files.size(Paths.get(filePathFull)) > 0) {
return true;
}
else {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
}
catch (IOException e) {
}
return false;
}
});
}
catch (TimeoutException e) {
}
}
总是存在一个.part文件,直到下载完成,原始文件(在我的示例中为csv)的大小为零。