【问题标题】:Is there a Selenium wait until download complete?是否有 Selenium 等到下载完成?
【发布时间】:2020-09-30 14:32:55
【问题描述】:

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

我现在的问题是下载时间太长了,我的代码已经继续这个过程了。如何在文件下载之前暂停代码?

是否有 selenium 等待下载完成,或者 selenium 将下载的文件名传递到一个变量中,我可以插入来自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)

【问题讨论】:

    标签: python-3.x selenium automated-tests


    【解决方案1】:

    您问题的明确答案是。 Selenium 没有这样的方法来等待下载完成。

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

    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
    

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

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

    【讨论】:

      【解决方案2】:

      如果在下载完成后发生 DOM 更改事件,那么您可以使用 selenium 预定义等待来等待该事件,否则唯一的选择是等到文件存在于您问题中链接中提到的位置.

      【讨论】:

        猜你喜欢
        • 2023-01-28
        • 2014-05-27
        • 2015-03-14
        • 2019-11-06
        • 2018-05-25
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多