当前位置: 首页 > 知识库问答 >
问题:

如何使用Jsoup替换each标记中的“text”

江飞章
2023-03-14

我有以下HTML:

<html>
<head>
</head>
<body>
    <div id="content" >
         <p>text <strong>text</strong> text <em>text</em> text </p>
    </div>
</body>    
</html>
<html>
<head>
</head>
<body>
    <div id="content" >
         <p>word <strong>word</strong> word <em>word</em> word </p>
    </div>
</body>    
</html>
    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
            }
        }
    }

共有2个答案

惠志
2023-03-14
相关问题
漆雕亮
2023-03-14
    String html = "<html> ...";
    Document doc = Jsoup.parse(html);
    Elements p = doc.select("div#content > p");
    p.html(p.html().replaceAll("text", "word"));
    System.out.println(doc.toString());

div#content>p表示元素

中的元素

的id是content

如果要仅替换text中的文本:

    Elements p = doc.select("div#content > p > strong");
    p.html(p.html().replaceAll("text", "word"));

 类似资料:
  • 这是我的密码 我想替换字体标签,并把span标签。在这将取代第一个字体标签但不是第二个标签

  • 您好,我已经尝试了以下答案:如何使用jsoup替换标记,以及如何使用jsoup替换HTML标记,但都没有成功。我正在用JSoup解析一个网站,我运行了一个accross-letter-look GIF图像。幸运的是,这些gif图像有一个特定的名称,例如字母“a”的a.gif。 HTML输入: 期望输出: 我的java代码(以下)未打印预期输出: 谢谢你的帮助。

  • 有没有人知道如何使用JSoup替换元素。我试图用按钮替换表格元素及其内容,但没有成功。代码尝试如下。这是一个Android项目

  • 我只需要帮助替换alt标签中的-(而不是代码/html的其余部分)。 错误:alt=“允许滚筒干燥” 良好:alt=“允许滚筒干燥” 我使用的是ATOM,而REGEXP教程对我来说是陌生的。(看起来很奇怪) 任何帮助都将不胜感激。 最终,我也会瞄准标题标签,但我需要一个领先的开始

  • 下面是我已经尝试过的代码: 有什么技巧或解决办法我可以实现它?

  • 问题内容: 我有以下模板字符串:。 我还具有用于名称,发票编号和到期日的String变量-用变量替换模板中的标记的最佳方法是什么? (请注意,如果变量恰好包含令牌,则不应将其替换)。 编辑 感谢@laginimaineb和@ alan-moore, 这是我的解决方案: 问题答案: 最有效的方法是使用匹配器连续查找表达式并替换它们,然后将文本附加到字符串生成器中: