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

GitLab Runner中Selenium下载文件的存储位置排查

问题诊断与解决方案

核心原因分析

你的测试在GitLab Runner环境中失败,本质是服务账号的默认下载目录权限/存在性问题,加上Chrome下载路径未显式配置,导致文件根本没成功下载到预期位置。

逐一排查与修复步骤

1. 检查服务账号的systemprofile/Downloads目录

GitLab Runner以Windows服务账号运行时,默认使用C:\Windows\system32\config\systemprofile作为用户目录,但这个目录下的Downloads文件夹默认可能不存在,即使存在,服务账号也可能没有读写权限:

  • 手动创建该目录:C:\Windows\system32\config\systemprofile\Downloads
  • 给服务账号(通常是NT AUTHORITY\LocalService或你指定的服务账号)分配该目录的读写权限

不过更推荐的是显式指定下载路径到流水线工作目录,避免依赖系统账号的默认目录。

2. 显式配置Chrome的下载路径

在Selenium的ChromeOptions中,强制指定下载到GitLab Runner的项目工作目录(比如${CI_PROJECT_DIR}/downloads),确保Runner有权限读写。Java代码示例:

ChromeOptions options = new ChromeOptions();
// 无头模式必备参数(如果流水线用无头Chrome)
options.addArguments("--headless=new");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--no-sandbox");

// 构建项目内的下载目录
String projectDir = System.getProperty("user.dir");
String downloadDir = projectDir + "\\downloads";
File downloadFolder = new File(downloadDir);
if (!downloadFolder.exists()) {
    downloadFolder.mkdirs();
}

// 配置Chrome下载偏好
Map<String, Object> chromePrefs = new HashMap<>();
chromePrefs.put("download.default_directory", downloadDir);
chromePrefs.put("download.prompt_for_download", false); // 禁用下载提示
chromePrefs.put("download.directory_upgrade", true);
chromePrefs.put("plugins.always_open_pdf_externally", true); // 直接下载PDF,不打开

options.setExperimentalOption("prefs", chromePrefs);

// 初始化Driver
WebDriver driver = new ChromeDriver(options);

3. 检查GitLab Runner服务的桌面交互权限

如果测试依赖Chrome的UI交互(即使无头模式),需要确保GitLab Runner服务开启了“允许服务与桌面交互”:

  • 打开Windows服务管理器,找到gitlab-runner服务
  • 右键→属性→登录选项卡,勾选“允许服务与桌面交互”
  • 重启服务

4. 增加下载等待逻辑

流水线环境的网络或页面加载速度可能比本地慢,测试代码中需要等待文件完全下载完成后再验证:

public static boolean waitForFile(String filePath, int timeoutSeconds) {
    File targetFile = new File(filePath);
    long timeout = System.currentTimeMillis() + (timeoutSeconds * 1000);
    
    while (System.currentTimeMillis() < timeout) {
        if (targetFile.exists() && targetFile.length() > 0) { // 确保文件已写入完成
            return true;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
    return false;
}

5. 验证GitLab Runner的执行权限

确认GitLab Runner使用的服务账号对项目工作目录(builds\<token>\<ID>\gitlab\<project>\<projectname>)有读写权限:

  • 右键该目录→属性→安全选项卡
  • 添加服务账号,分配“读取&写入”权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:43:15