等待下载完成selenium webdriver JAVA

qae*_*epk 14 java selenium-webdriver

单击下载按钮后,将下载文件.在执行下一个代码之前,需要等到下载完成.我的代码看起来像这样:

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();
Run Code Online (Sandbox Code Playgroud)

如何使webdriver等到下载完成?

小智 15

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

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

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

    element = driver.find_element_by_id('dl_link')
    url = element.get_attribute('href')
Run Code Online (Sandbox Code Playgroud)

从这里您可以使用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)
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这在适用时非常好。我处理的很多网站都不使用像将文件放在 `href` 这样简单的东西,但如果他们这样做了,那就太好了。 (3认同)
  • 这个没有错,我以前也用过这个方法。为了使这项工作与身份验证一起工作,您可以从 selenium 的驱动程序获取 cookie 并将其附加到 http 请求。但是,当下载链接是由js生成时,就很痛苦了。而且您也无法测试单击下载按钮是否确实下载了文件。我切换回正常状态,单击按钮并循环执行“file.exists()”检查。对于中心节点架构中的 selenium,我使用“ssh”来“ls”或“dir”文件的存在。 (2认同)

小智 7

do {

   filesize1 = f.length();  // check file size
   Thread.sleep(5000);      // wait for 5 seconds
   filesize2 = f.length();  // check file size again

} while (length2 != length1); 
Run Code Online (Sandbox Code Playgroud)

其中f是文件,文件大小很长


Ale*_*dar 7

我使用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
      }
    )
  }
Run Code Online (Sandbox Code Playgroud)

然后在我需要下载xls文件的测试套件中,我有以下内容:

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

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


Man*_*amy 6

下面的代码对我来说工作得很好。

由于我使用了通用类型并且按照建议,也不会发出任何警告Duration

File file = new File("C:\\chromedriver_win32.zip");
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(25)).pollingEvery(Duration.ofMillis(100));
wait.until( x -> file.exists());
Run Code Online (Sandbox Code Playgroud)


vin*_*ins 5

我喜欢等待

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

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


oly*_*lyv 4

好吧,你的文件存储在某个地方,对吧?所以,检查它是否存在于文件系统中

File f = new File(filePathString);

do {
  Thread.sleep(3000);
} while (f.exists() && f.length() == expectedSizeInBytes)
Run Code Online (Sandbox Code Playgroud)