You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Selenium中如何验证文件下载完成后再关闭WebDriver?

解决Selenium中动态文件名的文件下载等待问题

核心思路

  • 提前配置浏览器自动下载到指定目录,规避下载弹窗干扰
  • 点击下载前记录下载目录的已有文件,作为判断基准
  • 循环监控下载目录,直到新文件出现且文件大小稳定(确认下载完成)

步骤1:配置Edge浏览器自动下载设置

在初始化EdgeDriver前,添加下载配置,指定固定下载路径并关闭弹窗:

import org.openqa.selenium.edge.EdgeOptions;
import java.util.Map;

// ... 其他原有导入代码

public class sftest2 {
    public static void main(String[] args) throws IOException, InterruptedException, AWTException {
        // 设置驱动路径
        System.setProperty("webdriver.edge.driver", "D:\\Installer\\msedgedriver.exe");
        
        // 配置Edge下载参数
        String downloadDir = "D:\\你的实际下载目录"; // 替换为你的下载路径
        EdgeOptions options = new EdgeOptions();
        options.addArguments(String.format("--download-dir=%s", downloadDir));
        options.setExperimentalOption("prefs", Map.of(
            "download.default_directory", downloadDir,
            "download.prompt_for_download", false,
            "download.directory_upgrade", true,
            "safebrowsing.enabled", true
        ));
        
        // 初始化带配置的浏览器驱动
        WebDriver driver = new EdgeDriver(options);
        driver.manage().window().maximize();
        
        // ... 后续原有代码
    }
}

步骤2:编写下载等待工具方法

添加静态方法用于监控下载目录,等待新文件出现并完成:

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class sftest2 {
    // 新增等待下载完成的工具方法
    private static File waitForFileDownload(String downloadDir, List<File> initialFiles, long timeoutSeconds) throws InterruptedException {
        File dir = new File(downloadDir);
        long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds);
        
        while (System.currentTimeMillis() < endTime) {
            File[] currentFiles = dir.listFiles();
            if (currentFiles == null) continue;
            
            // 遍历目录找出新文件
            for (File file : currentFiles) {
                // 跳过下载中的临时文件(Edge临时文件后缀为.tmp/.part)
                if (file.getName().endsWith(".tmp") || file.getName().endsWith(".part")) {
                    continue;
                }
                // 确认是新出现的文件
                if (!initialFiles.contains(file)) {
                    // 等待文件大小连续2次一致,确认下载完成
                    long lastSize = 0;
                    int stableCount = 0;
                    while (stableCount < 2) {
                        long currentSize = file.length();
                        if (currentSize == lastSize) {
                            stableCount++;
                        } else {
                            lastSize = currentSize;
                            stableCount = 0;
                        }
                        TimeUnit.MILLISECONDS.sleep(500);
                    }
                    return file;
                }
            }
            TimeUnit.MILLISECONDS.sleep(1000);
        }
        throw new RuntimeException("文件下载超时");
    }

    // ... main方法及其他原有代码
}

步骤3:替换原有Thread.sleep逻辑

修改原代码中下载后的等待逻辑,替换固定时长的Thread.sleep:

// ... 原代码中的if判断块
if(driver.getPageSource().contains("View 1 -"))
{
    String downloadDir = "D:\\你的实际下载目录"; // 和配置中的路径一致
    File dir = new File(downloadDir);
    // 记录下载前的目录文件列表
    List<File> initialFiles = Arrays.asList(dir.listFiles());
    
    // 点击下载按钮
    driver.findElement(By.xpath("//*[@id='downloadReport']/div")).click();
    
    try {
        // 等待下载完成,超时设置为60秒(可按需调整)
        File downloadedFile = waitForFileDownload(downloadDir, initialFiles, 60);
        System.out.println("下载完成,文件路径:" + downloadedFile.getAbsolutePath());
    } catch (RuntimeException e) {
        System.err.println("下载超时或失败:" + e.getMessage());
        // 可添加失败后的处理,比如截图
    }
    
    // 下载完成后执行后续操作
    driver.findElement(By.xpath("//*[@id='footer-container']/div[3]/a")).click();
}

注意事项

  • 确保下载目录有读写权限,路径配置前后一致
  • 不同浏览器的临时文件后缀不同:Chrome为.crdownload,Edge为.tmp/.part,需对应调整判断逻辑
  • 超时时间可根据文件大小和网络环境灵活修改

内容的提问来源于stack exchange,提问作者mps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:45:45