Wait for Download to finish in selenium webdriver JAVA

后端 未结 13 1682
醉话见心
醉话见心 2020-12-01 14:38

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:

<
13条回答
  •  温柔的废话
    2020-12-01 14:53

    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.

提交回复
热议问题