在 selenium webdriver JAVA 中等待下载完成 [英] Wait for Download to finish in selenium webdriver JAVA

查看:64
本文介绍了在 selenium webdriver JAVA 中等待下载完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击下载按钮后,文件将被下载.在执行下一段代码之前,需要等待下载完成.

Once clicking a download button, files will be downloaded. Before executing next code, it needs to wait until the download completes.

我的代码如下:

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();

如何让网络驱动程序等待下载完成?

How can I make the webdriver wait until a download completes?

推荐答案

有点晚了,但这个问题有很多观点,我认为如果你还没有继续或其他人遇到了它.

A little late but this question has a good number of views, I thought it would be worth the time to answer it in case you haven't moved on or someone else comes across it.

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

I too ran into the same problem and thought I'd share. I was developing in python at the time but the same concept applies. You don't have to do the actual download using selenium. Rather than clicking on the element to start the download, you should consider retrieving the link and using built in functions to proceed from there.

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

The element you would normally click to begin the download should have a 'href' attribute that you should be able to read using selenium. This is the url pointing to the actual file. In python, it looks something like this:

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

从这里您可以使用 http 库来调用 url.这里的重要部分是您将 'stream' 设置为 true,以便您可以开始将字节写入文件.确保文件路径包含正确的文件扩展名和另一件事,大多数操作系统不允许您使用某些字符命名文件,例如反斜杠或引号,因此请注意这一点.

From here you can use an http library to call the url. The important part here is that you set 'stream' to true so you can begin writing the bytes to a file. Make sure the file path contains the correct file extension and another thing, most operating systems don't allow you to name files with certain characters such as back slashes or quotations so heads up on that.

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)

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

The program shouldn't continue until the download is complete making it no longer necessary to poll until it is complete.

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

I apologize for answering in a different language, in Java I believe you can use the HttpURLConnection API. Hope this helps!

这篇关于在 selenium webdriver JAVA 中等待下载完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆