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

如何用JSoup为HTML文档中所有<h2>标签添加<a>标签

用JSoup在Java 11中处理HTML的

标签(添加/完善内部标签)

场景示例

场景1:已有标签但无id的

原始HTML:

<h2><a>第一章:入门指南</a></h2>

处理后:

<h2><a id="section-1-第一章入门指南">第一章:入门指南</a></h2>

场景2:无标签的

原始HTML:

<h2>第二章:核心概念 <small>基础必看</small></h2>

处理后:

<h2><a id="section-2-第二章核心概念">第二章:核心概念 <small>基础必看</small></a></h2>

Java 11 + JSoup实现代码

先确保项目引入JSoup依赖(以Maven为例):

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.17.2</version> <!-- 使用最新稳定版 -->
</dependency>

处理逻辑代码:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.List;

public class H2LinkProcessor {
    public static void main(String[] args) {
        // 示例HTML内容
        String html = """
                <html>
                    <body>
                        <h2><a>第一章:入门指南</a></h2>
                        <h2>第二章:核心概念 <small>基础必看</small></h2>
                        <h2><a id="existing-id">第三章:高级技巧</a></h2>
                    </body>
                </html>
                """;

        // 解析HTML文档
        Document doc = Jsoup.parse(html);

        // 遍历所有<h2>元素
        List<Element> h2Elements = doc.select("h2");
        int sectionCounter = 1;

        for (Element h2 : h2Elements) {
            Element existingLink = h2.selectFirst("a");

            if (existingLink != null) {
                // 处理已有<a>的情况:检查并添加id
                if (!existingLink.hasAttr("id")) {
                    String id = generateUniqueId(h2.text(), sectionCounter);
                    existingLink.attr("id", id);
                }
            } else {
                // 处理无<a>的情况:创建新<a>并转移子节点
                Element newLink = new Element("a");
                String id = generateUniqueId(h2.text(), sectionCounter);
                newLink.attr("id", id);

                // 将<h2>的所有子节点移到新<a>中
                List<Node> childNodes = h2.childNodes();
                for (Node node : childNodes) {
                    newLink.appendChild(node);
                }

                // 将新<a>添加回<h2>
                h2.appendChild(newLink);
            }

            sectionCounter++;
        }

        // 输出处理后的HTML
        System.out.println(doc.html());
    }

    // 生成唯一id:基于标题文本和计数器做简单slug化
    private static String generateUniqueId(String title, int counter) {
        // 去除特殊字符、替换空格为连字符,结合计数器确保唯一
        String cleanTitle = title.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "")
                .replaceAll("\\s+", "-")
                .toLowerCase();
        return "section-" + counter + "-" + cleanTitle;
    }
}

代码说明

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:55:23