本文介绍了使用JSoup用字母替换标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我试过这些答案:和替换HTML标记到我的案例失败。我正在解析一个网站与JSoup和我跑的letter-look GIF图像。幸运的是,这些gif图像有一个特定的名称,例如。 a。输入字母A。

Hello I have tried these answers: How to replace a tag using jsoup and Replace HTML tags using jsoup to my case unsuccessfully. I am parsing a website with JSoup and I ran accross letter-look GIF images. Fortunately those gif images have a specific name, e.g. a.gif for letter "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代码(下面)不打印预期输出:

My java code (below) does not print the expected output:

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 而不是元素。 >

Using TextNode instead of 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。

The above code can print html as you expected.

这篇关于使用JSoup用字母替换标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:19
查看更多