如何通过Maven从Nexus仓库获取适配多系统的Chrome Driver可执行文件
适配Nexus获取ChromeDriver的可行方案
方案1:将ChromeDriver打包为私有依赖托管到Nexus
- 你可以将各操作系统、各版本的ChromeDriver二进制文件打包成Maven/Gradle格式的依赖包,上传到企业内部Nexus私有仓库,按平台维度区分坐标即可,坐标示例参考:
- Windows x64版本:
com.google.chromedriver:chromedriver-win64:125.0.6422.60 - Linux x64版本:
com.google.chromedriver:chromedriver-linux64:125.0.6422.60 - Mac ARM64版本:
com.google.chromedriver:chromedriver-mac-arm64:125.0.6422.60
- Windows x64版本:
- 项目中通过构建工具的profile配置,根据运行环境自动引入对应平台的依赖,无需将二进制文件提交到项目代码库。Maven profile配置示例如下:
<profiles> <profile> <id>windows-x64</id> <activation> <os> <family>windows</family> <arch>amd64</arch> </os> </activation> <dependencies> <dependency> <groupId>com.google.chromedriver</groupId> <artifactId>chromedriver-win64</artifactId> <version>${chromedriver.version}</version> </dependency> </dependencies> </profile> <!-- Linux、Mac系统的profile按同样规则配置即可 --> </profiles>
- 你可以编写简单的定时脚本,定期拉取官方最新版ChromeDriver自动打包上传到Nexus,保证仓库内的驱动版本保持最新。
方案2:配置Nexus Raw代理仓库缓存ChromeDriver
该方案无需手动打包上传驱动,更适合需要频繁更新版本的场景
- 在Nexus中新建Raw类型的代理仓库,指向ChromeDriver官方下载源,Nexus会自动缓存所有请求过的驱动文件,后续请求直接走内网链路。
- 项目内编写轻量工具类,测试运行前先检测本地缓存目录是否存在匹配版本的ChromeDriver,不存在则从Nexus代理仓库拉取对应系统版本的二进制文件到本地缓存,再配置
webdriver.chrome.driver系统变量指向文件路径即可。工具类逻辑示例如下:
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class ChromeDriverLoader { // 替换为企业内部Nexus Raw代理仓库地址 private static final String NEXUS_REPO_PREFIX = "http://内部Nexus地址/repository/chromedriver-proxy/"; private static final String CACHE_PATH = System.getProperty("user.home") + File.separator + ".cache" + File.separator + "chromedriver"; public static void initChromeDriver(String chromeMajorVersion) throws IOException { // 自动识别当前操作系统 String os = System.getProperty("os.name").toLowerCase(); String osType = os.contains("win") ? "win64" : os.contains("linux") ? "linux64" : "mac-arm64"; String suffix = os.contains("win") ? ".exe" : ""; String driverFileName = "chromedriver" + suffix; // 检查本地缓存是否存在 File targetFile = new File(CACHE_PATH + File.separator + chromeMajorVersion + File.separator + osType + File.separator + driverFileName); if (targetFile.exists()) { System.setProperty("webdriver.chrome.driver", targetFile.getAbsolutePath()); return; } // 从Nexus拉取驱动到本地缓存 Files.createDirectories(Paths.get(targetFile.getParent())); String downloadUrl = NEXUS_REPO_PREFIX + chromeMajorVersion + "/" + osType + "/chromedriver-" + osType + suffix; try (InputStream inputStream = new URL(downloadUrl).openStream()) { Files.copy(inputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } // 赋予驱动执行权限 targetFile.setExecutable(true); System.setProperty("webdriver.chrome.driver", targetFile.getAbsolutePath()); } }
- 测试启动前调用
ChromeDriverLoader.initChromeDriver("你的Chrome大版本号")即可完成驱动初始化,你也可以扩展工具类逻辑,自动识别本地安装的Chrome版本,无需手动传入版本参数。
内容的提问来源于stack exchange,提问作者hussainsm
相关产品推荐
相关产品推荐

