Once clicking a download button, files will be downloaded. Before executing next code, it needs to wait until the download completes.
My code looks like this:
<This one worked for me:
Path filePath = Paths.get("path/to/file/fileName.pdf");
File file = filePath.toFile();
void waitForFileDownloaded(File file, int timeoutSeconds) {
WebDriver driver = getDriver();
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(timeoutSeconds))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
wait.until((webDriver) -> file.exists());
}
I use Scala for my automation but the port to Java should be trivial since I use java Selenium classes there anyway. So, first you need this:
import com.google.common.base.Function
import java.nio.file.{Files, Paths, Path}
def waitUntilFileDownloaded(timeOutInMillis:Int)={
val wait:FluentWait[Path] = new FluentWait(Paths.get(downloadsDir)).withTimeout(timeOutInMillis, TimeUnit.MILLISECONDS).pollingEvery(200, TimeUnit.MILLISECONDS)
wait.until(
new Function[Path, Boolean] {
override def apply(p:Path):Boolean = Files.list(p).iterator.asScala.size > 0
}
)
}
Then in my test suite where I need to download xls file I just have this:
def exportToExcel(implicit driver: WebDriver) = {
click on xpath("//div[contains(@class, 'export_csv')]")
waitUntilFileDownloaded(2000)
}
I hope you've got the idea. FluentWait is very useful abstraction and though it is a part of Selenium it can be used wherever you need to wait with polling till some condition is met.
The below code is working fine for me.
Also no warning will be as I used Generic type and Duration as recommended.
File file = new File("C:\chromedriver_win32.zip"); FluentWait wait = new FluentWait(driver).withTimeout(Duration.ofSeconds(25)).pollingEvery(Duration.ofMillis(100)); wait.until( x -> file.exists());
Some operating systems (e.g. Mac OS X) don't set the filename until the download is complete. So it seems sufficient to use a wait or a while loop to check for the file to exist.
e.g.
File file = new File(fullPathToFile);
while (!file.exists()) {
Thread.sleep(1000);
}
do {
filesize1 = f.length(); // check file size
Thread.sleep(5000); // wait for 5 seconds
filesize2 = f.length(); // check file size again
} while (length2 != length1);
where f is a File, filesize is long
import time
from os import walk
download_dir = 'path\\to\\download\\folder'
def check_if_download_folder_has_unfinished_files():
for (dirpath, dirnames, filenames) in walk(download_dir):
return str(filenames)
def wait_for_files_to_download():
time.sleep(5) # let the driver start downloading
file_list = check_if_download_folder_has_unfinished_files()
while 'Unconfirmed' in file_list or 'crdownload' in file_list:
file_list = check_if_download_folder_has_unfinished_files()
time.sleep(1)
if __name__ == '__main__':
wait_for_files_to_download()