我通过chromewebdriver(windows)使用selenium和python,以自动完成从不同页面下载大量文件的任务.

我不得不使用静态等待来等待下载完成(丑陋).我无法判断文件系统来验证下载何时完成,因为我使用多线程(一次从不同页面下载大量文件),而且文件名在网站本身中动态生成.

我的代码:

def file_download(num, drivervar):
Counter += 1
    try:
        drivervar.get(url[num])
        download_button = WebDriverWait(drivervar, 20).until(EC.element_to_be_clickable((By.ID, 'download button ID')))
        download_button.click()
        time.sleep(10) 
    except TimeoutException: # Retry once
        print('Timeout in thread number: ' + str(num) + ', retrying...')
..... 

是否可以在webdriver中确定下载完成?我想避免浪费时间.睡眠(x).

谢谢.

推荐答案

每个驱动程序的访问状态都是chrome://downloads/.

要等待所有下载完成并列出所有路径:

def every_downloads_chrome(driver):
    if not driver.current_url.startswith("chrome://downloads"):
        driver.get("chrome://downloads/")
    return driver.execute_script("""
        var items = document.querySelector('downloads-manager')
            .shadowRoot.getElementById('downloadsList').items;
        if (items.every(e => e.state === "COMPLETE"))
            return items.map(e => e.fileUrl || e.file_url);
        """)


# waits for all the files to be completed and returns the paths
paths = WebDriverWait(driver, 120, 1).until(every_downloads_chrome)
print(paths)

已更新以支持版本81之前的更改.

Python-3.x相关问答推荐

"安装serial vs安装psyserial header,"""

为什么我在BLE中的广告代码在发送包裹之间需要大约1秒

CSV-DAT 转换时将引号添加到数据中

根据按不同列中的值分组的平均值划分 DataFrame

将数据框中的值与另一个数据框中的多列进行比较,以获取条目以有效方式匹配的列表列表

如何在不使用循环的情况下根据另一个数组的索引值将 numpy 数组中不同通道的值设置为零?

根据另一个数据帧中的位置从主数据帧中提取子序列

多进程:两个进程,一起杀死

Python:如何从句子/段落中提取地址(非正则表达式方法)?

使用大型多个数据集,其中每个数据集包含多个值 - Pytorch

列表中的重复数字与列表理解

从 yahoo Finance python 一次下载多只股票

运行 PyCharm 测试时如何解决django.core.exceptions.ImproperlyConfigured:找不到 GDAL 库?

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

sys.stdin.readline() 和 input():读取输入行时哪个更快,为什么?

如何在 Python 中计算两个包含字符串的列表的 Jaccard 相似度?

在 Python 3 中获取所有超类

python中的绝对导入是什么?

如何将发音相似的词放在一起

如何阻止散景在 Jupyter Notebook 中打开新标签?