你好,我试过这些答案:How to replace a tag using jsoupReplace HTML tags using jsoup对我的案子都没有成功。我正在用JSoup解析一个网站,我运行了accross-letter-look GIF图像。幸运的是,这些gif图像有一个特定的名称,例如a.gif代表字母“a”。
HTML输入:

<body>
  <p><img src="http://www.example.com/images/a.gif" align="left">mong us!</p>
</body>

期望输出:
<body>
  <p>Among us!</p>
</body>

我的java代码(如下)未打印预期输出:
Document document = Jsoup.connect("http://www.example.com").get();
if(document.select("img").attr("src").contains("a.gif"))
  {
    document.select("img").get(0).replaceWith(new Element(Tag.valueOf("img"), "A"));
  }

谢谢你的帮助。

最佳答案

使用TextNode而不是Element

Document document = Jsoup.parse(html);
if (document.select("img").get(0).attr("src").contains("a.gif")) {
    document.select("img").get(0).replaceWith(new TextNode("A", ""));
    System.out.println(document);
}

上面的代码可以按预期打印html。

关于java - 使用JSoup用字母替换标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18346962/

10-13 01:13