等待下载完成selenium webdriver JAVA

单击下载按钮后,将下载文件。 在执行下一个代码之前,需要等到下载完成。 我的代码如下所示:

Thread.sleep(2000); driver.findElement(By.xpath("//*[@id='perform']")).click();//click for download Thread.sleep(20000); //code to be executed after download completes Readfile fileobj=new Readfile(); String checkfile=fileobj.checkfilename(); 

如何让webdriver等到下载完成?

有点晚了,但这个问题有很多观点,我认为如果你没有继续前进或其他人碰到它,那么值得花时间回答它。

我也遇到了同样的问题,并认为我会分享。 我当时正在使用python进行开发,但同样的概念也适用。 您不必使用selenium进行实际下载。 您应该考虑检索链接并使用内置函数从那里继续,而不是单击元素以开始下载。

您通常单击以开始下载的元素应该具有您应该能够使用selenium读取的’href’属性。 这是指向实际文件的URL。 在python中,它看起来像这样:

  element = driver.find_element_by_id('dl_link') url = element.get_attribute('href') 

从这里您可以使用http库来调用URL。 这里的重要部分是你将’stream’设置为true,这样你就可以开始将字节写入文件。 确保文件路径包含正确的文件扩展名和其他内容,大多数操作系统不允许您为具有某些字符的文件命名,例如反斜线或引号,以便对此进行操作。

 def download_file(url, file_path): from requests import get reply = get(url, stream=True) with open(file_path, 'wb') as file: for chunk in reply.iter_content(chunk_size=1024): if chunk: file.write(chunk) 

在下载完成之前,程序不应继续,因此在完成之前不再需要轮询。

我为用不同的语言回答道歉,在Java中我相信你可以使用HttpURLConnection API。 希望这可以帮助!

 do { filesize1 = f.length(); // check file size Thread.sleep(5000); // wait for 5 seconds filesize2 = f.length(); // check file size again } while (length2 != length1); 

其中f是文件,filesize很长

我使用Scala进行自动化,但Java的端口应该是微不足道的,因为我在那里使用java Selenium类。 所以,首先你需要这个:

 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 } ) } 

然后在我需要下载xls文件的测试套件中,我就是这样:

 def exportToExcel(implicit driver: WebDriver) = { click on xpath("//div[contains(@class, 'export_csv')]") waitUntilFileDownloaded(2000) } 

我希望你有这个主意。 FluentWait是非常有用的抽象,虽然它是Selenium的一部分,但它可以在任何需要等待轮询的地方使用,直到满足某些条件。

好吧,你的文件存放在某个地方,对吗? 因此,检查它是否存在于文件系统中

 File f = new File(filePathString); do { Thread.sleep(3000); } while (f.exists() && f.length() == expectedSizeInBytes) 

适用于Alexander Arendar的java改编:

(使用Java 8和FluentWait的until方法的谓词版本)

  private void waitForFileDownload(int totalTimeoutInMillis, String expectedFileName) throws IOException { FluentWait 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; } 

注意使用createTempDirectory来避免递归删除超过预期的警告以及在我们完成它时自动安全地处理文件夹。

某些操作系统(例如Mac OS X)在下载完成之前不会设置文件名。 因此,使用wait或while循环检查文件是否存在似乎已足够。

例如

 File file = new File(fullPathToFile); while (!file.exists()) { Thread.sleep(1000); } 

我喜欢awaitility

  Path filePath = Paths.get(".", "filename"); await().atMost(1, MINUTES) .ignoreExceptions() .until(() -> filePath.toFile().exists()); 

更多信息: http : //www.testautomationguru.com/selenium-webdriver-how-to-wait-for-expected-conditions-using-awaitility/