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

如何在Ubuntu 20.04中用Selenium WebDriver正确设置Chrome默认下载路径?

解决跨平台下载路径兼容问题

问题出在你硬编码了Windows的路径分隔符\,Ubuntu系统只识别正斜杠/,导致生成的路径混合了两种分隔符,Chrome无法识别这个无效路径。

给你三种可靠的解决方式:

1. 使用File.separator自动适配系统

Java提供了File.separator常量,会根据当前运行的系统自动返回对应的分隔符(Windows是\,Linux是/)。修改代码如下:

import java.io.File;
// ...
HashMap<String, Object> hashmap = new HashMap<>();
String defaultPath = System.getProperty("user.dir") 
        + File.separator + "src" 
        + File.separator + "main" 
        + File.separator + "resources";
hashmap.put("download.default_directory", defaultPath);
options.setExperimentalOption("prefs", hashmap);

2. 使用Paths类拼接路径(Java 7+推荐)

Paths.get()方法可以接收多个路径片段,自动处理跨平台的分隔符拼接,代码更简洁易读:

import java.nio.file.Paths;
// ...
HashMap<String, Object> hashmap = new HashMap<>();
String defaultPath = Paths.get(System.getProperty("user.dir"), "src", "main", "resources").toString();
hashmap.put("download.default_directory", defaultPath);
options.setExperimentalOption("prefs", hashmap);

3. 手动替换分隔符(应急方案)

如果不想导入额外类,可以把路径里的反斜杠统一替换成正斜杠,这种方式虽然可行,但不如前两种优雅:

HashMap<String, Object> hashmap = new HashMap<>();
String defaultPath = (System.getProperty("user.dir") + "\\src\\main\\resources").replace("\\", "/");
hashmap.put("download.default_directory", defaultPath);
options.setExperimentalOption("prefs", hashmap);

用以上任意一种方法,生成的路径都会符合Ubuntu系统的要求,Chrome就能正确识别并使用指定的下载目录了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:25:24