要精确控制等待文件下载时间和判断文件是否下载完成,可以使用Selenium的WebDriverWait类来等待特定条件的出现或消失,并使用expected_conditions模块中的条件。

首先,使用find_elements_by_方法查找所有的文件下载元素,并将它们的链接存储在一个列表中。然后,使用循环遍历该列表,并依次点击每个链接进行下载。

在点击链接后,可以使用WebDriverWait类来等待文件是否下载完成。通过判断下载目录中是否出现该文件来判断文件是否下载成功。如果文件未下载成功,可以使用time.sleep方法来等待一段时间,然后再次判断文件是否下载成功。

如果文件下载失败超过设定的重试次数,可以选择跳过该文件并继续下一个文件的下载。

下面是一个示例代码,演示了如何实现上述功能:

import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 创建一个浏览器实例
driver = webdriver.Chrome()

# 设置文件下载路径
download_path = '/path/to/download/folder'
prefs = {'download.default_directory': download_path}
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', prefs)

# 循环爬取
while True:
    # 爬取页面并找到所有文件下载元素
    driver.get('https://example.com')
    download_elements = driver.find_elements_by_css_selector('.download-link')

    # 如果没有文件下载元素,则跳出循环
    if len(download_elements) == 0:
        break

    # 遍历文件下载元素并依次点击下载
    for element in download_elements:
        link = element.get_attribute('href')
        element.click()

        # 等待文件下载完成
        wait = WebDriverWait(driver, 120)
        file_path = download_path + '/filename.ext'
        try:
            wait.until(EC.presence_of_file(file_path))
            print('文件下载成功:', link)
        except:
            print('文件下载失败:', link)

            # 重试下载3次
            retries = 3
            while retries > 0:
                time.sleep(10)  # 等待10秒后再次判断文件是否下载成功
                if os.path.exists(file_path):
                    print('文件下载成功:', link)
                    break
                else:
                    retries -= 1
            else:
                print('文件下载失败超过重试次数:', link)

请注意,上述示例代码仅为演示目的,并未完全测试。您可能需要根据自己的需求进行适当的修改和调整

使用selenium模拟爬虫有一个脚本循环爬取当有多个文件下载元素需要依次根据link去点击点击就开始下载且文件下载需要时间有需要几秒有需要100秒且需要判断文件是否下载成功对未下载成功的文件需要重置下载3次怎么去精确控制等待文件下载时间和判断文件是否下载完成呢尽量避免使用oslistdir方法

原文地址: https://www.cveoy.top/t/topic/iqbn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录