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

Linux环境下Java版Selenium(4.5.3)无法将文件下载到指定目录

Ubuntu下Selenium ChromeDriver文件下载失效问题

我在Ubuntu 18.04.5 LTS (Bionic Beaver)系统中,基于Spring框架使用Selenium 4.5.3提取文档时遇到问题。这段代码在Windows下能正常将文件下载到指定目录,但在Linux下无任何报错,文件既没出现在指定目录,也不在默认目录里。变量downloadPath格式为/myMainDirectory/files。

代码如下:

private ChromeDriver instantiateDriver(boolean headless) {
        ChromeOptions co = new ChromeOptions();
        co.addArguments("--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors",
                "--disable-extensions", "--no-sandbox", "--disable-dev-shm-usage");

        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.default_directory", downloadPath + File.separator + "myDirectory");
        prefs.put("plugins.plugins_disabled", "Chrome PDF Viewer");
        prefs.put("plugins.always_open_pdf_externally", "True");
        prefs.put("download.prompt_for_download", "False");
        co.setExperimentalOption("prefs", prefs);
        co.setCapability("se:downloadsEnabled", true);
        if (headless)
            co.addArguments("--headless",
                    "--window-size=1920x1080)");
        ChromeDriver driver = null;
        try {
            driver = new ChromeDriver(co);
        } catch (SessionNotCreatedException e) {
            log.error("driver had some problems initing...");
        }
        return driver;
    }

排查与解决方向

  • 权限检查:确认/myMainDirectory/files/myDirectory目录存在,且运行Spring应用的用户有读写权限。Linux下如果目录由root创建,应用用普通用户运行会无法写入,可执行chown -R [用户名] /myMainDirectory/files和chmod -R 755 /myMainDirectory/files调整权限。
  • 修复无效参数:代码中--window-size=1920x1080)多了一个右括号,会导致参数失效,修正为--window-size=1920x1080。
  • 版本匹配验证:Selenium 4.5.3需要对应版本的ChromeDriver,检查Ubuntu上的Chrome版本,确保ChromeDriver与Chrome主版本完全一致。
  • 路径格式优化:Linux下直接用/拼接路径更稳妥,可将路径改为downloadPath + "/myDirectory",同时打印最终路径确认拼接正确,比如添加System.out.println("Download path: " + downloadPath + "/myDirectory");。
  • 补充headless参数:部分Linux环境下,headless模式需添加--disable-features=VizDisplayCompositor参数,否则会导致下载异常。
  • 检查默认下载目录:Linux下Chrome默认下载目录一般是~/.config/google-chrome/Default/Downloads,可以去这里确认文件是否被下载到了默认路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:23:15