如何使用 Jsoup 替换每个标签中的“文本”

2023-11-30

我有以下 html:

<html>
<head>
</head>
<body>
    <div id="content" >
         <p>text <strong>text</strong> text <em>text</em> text </p>
    </div>
</body>    
</html>

如何使用将每个标签中的“文本”替换为“单词”Jsoup图书馆。 我想看看:

<html>
<head>
</head>
<body>
    <div id="content" >
         <p>word <strong>word</strong> word <em>word</em> word </p>
    </div>
</body>    
</html>

感谢您的任何建议!

UPD:感谢您的回答,但我找到了通用的方法:

    Element entry = doc.select("div").first();
    Elements tags = entry.getAllElements();
    for (Element tag : tags) {
        for (Node child : tag.childNodes()) {
            if (child instanceof TextNode && !((TextNode) child).isBlank()) {
                System.out.println(child); //text
                ((TextNode) child).text("word"); //replace to word
            }
        }
    }

Document doc = Jsoup.connect(url).get();
String str = doc.toString();
str = str.replace("text", "word");

try it..

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Jsoup 替换每个标签中的“文本” 的相关文章

随机推荐