Python中如何使用selenium webdriver点击按钮下载文件并监听下载完成?

Python中如何使用selenium webdriver点击按钮下载文件并监听下载完成?

5 回复

selenium 只能监听 html,除非下载成功后网页有变化


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_with_monitoring(download_dir, button_locator, timeout=60):
    """
    点击按钮下载文件并监控下载完成
    
    Args:
        download_dir: 下载目录路径
        button_locator: 按钮定位器 (By, value)
        timeout: 超时时间(秒)
    """
    # 设置Chrome下载选项
    options = webdriver.ChromeOptions()
    prefs = {
        "download.default_directory": download_dir,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing.enabled": True
    }
    options.add_experimental_option("prefs", prefs)
    
    driver = webdriver.Chrome(options=options)
    
    try:
        # 记录下载前的文件列表
        initial_files = set(os.listdir(download_dir))
        
        # 点击下载按钮
        wait = WebDriverWait(driver, 10)
        download_button = wait.until(EC.element_to_be_clickable(button_locator))
        download_button.click()
        
        # 监控下载完成
        start_time = time.time()
        while time.time() - start_time < timeout:
            current_files = set(os.listdir(download_dir))
            new_files = current_files - initial_files
            
            # 检查是否有.crdownload临时文件(Chrome下载中)
            temp_files = [f for f in new_files if f.endswith('.crdownload')]
            
            if new_files and not temp_files:
                print(f"下载完成!新文件: {list(new_files)}")
                return list(new_files)
            
            time.sleep(1)
        
        print("下载超时")
        return None
        
    finally:
        driver.quit()

# 使用示例
if __name__ == "__main__":
    # 配置参数
    DOWNLOAD_DIR = r"C:\Downloads"  # 替换为你的下载目录
    BUTTON_LOCATOR = (By.ID, "download-button")  # 替换为实际的按钮定位
    
    # 执行下载
    downloaded_files = download_file_with_monitoring(
        download_dir=DOWNLOAD_DIR,
        button_locator=BUTTON_LOCATOR,
        timeout=60
    )

这个方案的核心是:先记录下载前的文件列表,点击按钮后轮询检查目录变化。关键点在于识别Chrome的临时文件(.crdownload扩展名),当新文件出现且没有临时文件时,说明下载完成。

注意替换DOWNLOAD_DIR和BUTTON_LOCATOR为你实际的值。按钮定位器可以是任何Selenium支持的定位方式,比如(By.XPATH, “//button[text()=‘下载’]”)。

一句话建议:用目录快照对比加临时文件检测来监控下载状态。

python 检测目录?

谷歌一下有人说的方法是周期性检测下载目录下面<filename>.part 文件是否存在

不用监听啊,下载是浏览器的事情,你接着做下一步操作就行了,即使下载失败,那也是网络慢,和自动化程序无关的

回到顶部