jsoup使用案例(HTML解析Java工具)
Java中比较推荐jsoup,非常地轻量。
jsoup支持使用跟前端一致的选择器语法来定位HTML的元素,比如类选择器、CSS选择器。
我们可以先通过类选择器找到最外层的元素dgControl,再通过CSS选择器imgmimg找到所有的图片元素
案例介绍:自动通过搜索引擎搜索图片并批量下载
这里我们使用了bing搜索引擎来搜索图片,我们打开bing的F12可以查看到对应的获取图片的接口
以及HTML结构
大致如图:

元素坐标:

导入坐标
<!-- HTML 解析:https://jsoup.org/ -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.3</version>
</dependency>
具体代码参考如下
@Override
public int uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
String searchText = pictureUploadByBatchRequest.getSearchText();
// 格式化数量
Integer count = pictureUploadByBatchRequest.getCount();
ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
// 要抓取的地址
String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
Document document;
try {
document = Jsoup.connect(fetchUrl).get();
} catch (IOException e) {
log.error("获取页面失败", e);
throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
}
Element div = document.getElementsByClass("dgControl").first();
if (ObjUtil.isNull(div)) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
}
Elements imgElementList = div.select("img.mimg");
int uploadCount = 0;
for (Element imgElement : imgElementList) {
String fileUrl = imgElement.attr("src");
if (StrUtil.isBlank(fileUrl)) {
log.info("当前链接为空,已跳过: {}", fileUrl);
continue;
}
// 处理图片上传地址,防止出现转义问题
int questionMarkIndex = fileUrl.indexOf("?");
if (questionMarkIndex > -1) {
fileUrl = fileUrl.substring(0, questionMarkIndex);
}
// 上传图片
PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
try {
PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
log.info("图片上传成功, id = {}", pictureVO.getId());
uploadCount++;
} catch (Exception e) {
log.error("图片上传失败", e);
continue;
}
if (uploadCount >= count) {
break;
}
}
return uploadCount;
}