是否有硒等待下载完成? [英] Is there a Selenium wait until download complete?

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

问题描述

我有一个程序,该程序使用selenium下载文件,然后使用 os.listdir 获取文件名.

I have a program that downloads a file using selenium and then gets the file name with os.listdir.

我现在的问题是下载时间太长,并且我的代码随着该过程继续进行.如何暂停代码,直到文件下载完毕?

My problem right now is that the download takes too long, and my code has moved on with the process. How can I pause the code until the file is downloaded?

是否有硒等待下载完成,或者硒将下载的文件名传递给变量的方法,我可以从

Is there a selenium wait until download complete, or a way for selenium to pass the downloaded files name into a variable that i can plug into the answer from here

driver.find_element(By.XPATH, '//button[text()="Export to CSV"]').click()
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Download"]')))
driver.find_element(By.XPATH, '//button[text()="Download"]').click()
files=os.listdir(folderPath)#finds all files in folder
print(files)

推荐答案

您问题的明确答案是.硒没有这种方法可以等到下载完成.

The clear answer of you question is No. Selenium don't have such method to wait until download get completed.

您可以编写自己的自定义方法,该方法可以在一定时间间隔内连续检查下载目录中的下载文件名.

You can write your own custom method which check downloaded file name in download directory continuously in some time interval.

def is_file_downloaded(filename, timeout=60):
    end_time = time.time() + timeout
    while not os.path.exists(filename):
        time.sleep(1)
        if time.time() > end_time:
            print("File not found within time")
            return False

    if os.path.exists(filename):
        print("File found")
        return True

在点击下载的代码行之后调用该方法.

Call that method just after code line which hits download.

driver.find_element(By.XPATH, '//button[text()="Download"]').click()
file_path = '/Users/narendra.rajput/Documents/30.docx'
if is_file_downloaded(file_path, 30):
    print("yes")
else:
    print("No")

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

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