Java将String类型的html文本中的img路径替换前缀

1.引入jsoup包

复制代码
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>

2.编写代码

复制代码
@Service
@Slf4j
public class ImgSrcReplaceServiceImpl implements ImgSrcReplaceService {

    /**
     * @param html html文本
     * @param newPrefix 要替换的前缀路径,路径记得最后+斜杠
     * */
    @Override
    public String ImgSrcReplace(String html,String  newPrefix) {
        log.info("开始解析");
        // 使用 Jsoup 解析 HTML
        Document document = Jsoup.parse(html);
        // 查找所有 img 标签
        Elements imgTags = document.select("img");
        // 修改 img 标签的 src 属性
        for (Element imgTag : imgTags) {
            String src = imgTag.attr("src");
            // 检查图片路径是否包含随机数,假设随机数存在于路径的前缀中
            if (src != null && !src.isEmpty()) {
                // 假设我们要替换路径的前缀部分,可以修改 "https://example.com/" 为新的前缀
//                String newPrefix = "https://zxd.com/"; // 你可以根据需要定义新的前缀
                String fileName = src.substring(src.lastIndexOf("/")); // 获取图片文件名(包含扩展名)
                // 构建新的 src 路径
                String newSrc = newPrefix + fileName;
                // 设置新的 src 属性
                imgTag.attr("src", newSrc);
            }
        }
        // 获取修改后的 HTML
        String updatedHtml = document.html();
        // 输出修改后的 HTML
        log.info(updatedHtml);
        return updatedHtml;
    }
}
相关推荐
wangruofeng36 分钟前
AI Models 1.1.0 发布,查大模型价格、对比模型和找 API 地址
前端·aigc·ai编程
wangruofeng39 分钟前
给前端开发者的 100 个设计参考网站
前端·设计
Pniubi3 小时前
怎么排查慢SQL,怎么解决?
java·数据库·sql
薛之谦_4 小时前
Java 全栈知识体系:从 IDEA 高效开发到 JVM、并发与 Stream 实战
java·jvm·intellij-idea
星栈4 小时前
视频即代码,Remotion 能做什么、不能做什么
前端·音视频开发
广州华水科技4 小时前
单北斗GNSS位移监测系统的应用与技术解析
前端
用户47949283569154 小时前
从一句话或代码仓到可交互 HTML:开源 Agent 画图技能 Archify v3.2 实测与选型边界
前端·后端·面试
风骏时光牛马6 小时前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng7 小时前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构
文丑颜不良啊8 小时前
LeetCode2761~2780题目解析
java·leetcode