你可以使用webdriver.support.ui.WebDriverWait来等待文件下载完成,然后使用os.path.getsize来获取文件大小,并根据文件大小来控制下载时间。

以下是一个示例代码,可以帮助你实现根据文件大小精确控制下载文件的过程,并记录下载失败的文件名:

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

def download_file(driver, element):
    element.click()
    time.sleep(1)  # 给文件下载一些时间

def is_file_downloaded(file_path):
    return os.path.exists(file_path)

def reset_download(driver):
    # 清空下载目录,重置下载状态
    driver.execute_script("window.open('about:blank');")
    driver.switch_to.window(driver.window_handles[-1])
    driver.execute_script("localStorage.clear();")
    driver.close()
    driver.switch_to.window(driver.window_handles[0])

def download_files(file_urls):
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, 10)

    for file_url in file_urls:
        # 点击查询按钮
        search_button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'button.search')))
        search_button.click()

        # 等待文件链接出现并点击下载
        file_link = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.file-link')))
        download_file(driver, file_link)

        # 等待文件下载完成
        file_path = '/path/to/downloaded/file'
        wait.until(lambda driver: is_file_downloaded(file_path))

        # 判断文件大小
        file_size = os.path.getsize(file_path)
        if file_size > 10*1024*1024:  # 如果文件大小大于10MB,等待更长的时间
            time.sleep(10)

        # 判断文件是否下载成功,如果失败则重置下载状态,并记录下载失败的文件名
        if not is_file_downloaded(file_path):
            reset_download(driver)
            print(f"Download failed: {file_url}")
        else:
            print(f"Download success: {file_url}")

    driver.quit()

# 示例代码的使用方法:
file_urls = ['http://example.com/file1.pdf', 'http://example.com/file2.pdf', 'http://example.com/file3.pdf']
download_files(file_urls)

请注意,你需要将示例代码中的'/path/to/downloaded/file'替换为你的实际下载文件的路径。另外,示例代码假设你使用的是Chrome浏览器,你需要根据实际情况选择适合的webdriver,并将webdriver的路径传递给webdriver.Chrome()

使用selenium模拟爬虫当输入参数点击查询会查询到多条数据每点击一条数据就是下载文件可以根据css selector定位link元素for遍历点击文件下载当文件下载时因文件大小会影响下载的时间长久怎么去精确控制根据文件的大小去设置下载文件的时候且需要判断文件是否下载成功当文件下载失败时需重置下载3次超过3次不予下载且记录下载失败文件名

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

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