快速使用selenium+java案例
前置ChromeDriver准备
ChromeDriver地址使用
ChromeDriver官方地址:https://googlechromelabs.github.io/chrome-for-testing/
示范官方下载地址:
https://storage.googleapis.com/chrome-for-testing-public/139.0.7258.66/linux64/chrome-linux64.zip
但是你若是直接用java api去请求可能会报连接不上的问题,我们这里选择使用国内镜像:
# 淘宝
https://registry.npmmirror.com/binary.html?path=chromedriver/# 华为
https://mirrors.huaweicloud.com/chromedriver/# 腾讯(无chrome driver)
https://mirrors.cloud.tencent.com/chromedriver/
我们这里使用华为云的:
https://mirrors.huaweicloud.com/chromedriver/138.0.7204.183/chromedriver-mac-arm64.zip
快速下载ChromeDriver & 设置可执行权限 & 环境变量
引入pom.xml依赖
这里我们引入hutool & selenium相关的依赖包:
<dependencies><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.35</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.25.0</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-chrome-driver</artifactId><version>4.25.0</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-api</artifactId><version>4.25.0</version></dependency><!-- 支持 触摸屏操作 的接口 --><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-remote-driver</artifactId><version>4.25.0</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.21</version> <!-- 或更高版本 --></dependency>
</dependencies>
工具类封装(HutoolUtil、ChromeDriverUtil)
HutoolUtil.java(封装下载 & 解压功能)
package com.changlu.autosyncblog.util;import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.compress.CompressUtil;
import cn.hutool.extra.compress.extractor.Extractor;
import cn.hutool.http.HttpRequest;/*** Hutool工具类,提供文件下载和解压缩功能* 该类使用Hutool库实现文件下载和解压缩操作。*/
public class HutoolUtil {/*** 下载文件到指定路径* @param fileUrl 文件的URL地址* @param downloadPath 下载后的文件保存路径*/public static void download(String fileUrl, String downloadPath) {HttpRequest.get(fileUrl).setFollowRedirects(true).header("User-Agent", "Mozilla/5.0").timeout(30_000).execute().writeBody(FileUtil.file(downloadPath));}/*** 解压缩文件到指定路径* @param downloadPath 下载的压缩文件路径* @param extractPath 解压后的文件保存路径*/public static void extract(String downloadPath, String extractPath) {Extractor extractor = CompressUtil.createExtractor(CharsetUtil.defaultCharset(),FileUtil.file(downloadPath));extractor.extract(FileUtil.file(extractPath));}}