首页 > 解决方案 > 使用 Jsoup 解析 HTML 以获取单个元素的文本

问题描述

我需要解析以下文本并为每个文本创建单独的对象。我尝试了几种方法来做到这一点,但它没有以我需要的格式提供结果。

正文是:

String text = "This is start of a text&nbsp;<a href=\"https://google.com/sample\">followed by a link&nbsp;sample</a>and ending with some text."

使用以下代码:

Document document = Jsoup.parse(text);
Elements elements = document.select("*");
for(Element e : elements){
System.out.println( e.tagName() + ": " + e.text());}

实际结果是

root: This is start of a text followed by a link sampleand ending with some text.
html: This is start of a text followed by a link sampleand ending with some text.
head: 
body: This is start of a text followed by a link sampleand ending with some text.
p: This is start of a text followed by a link sampleand ending with some text.
a: followed by a link sample

我需要得到以下结果,以便我可以为每个文本创建一个自定义对象

body: This is start of a text&nbsp;
a:followed by a link&nbsp;sample
body:and ending with some text.

标签: jsouphtml-parsing

解决方案


为了避免返回所有孩子使用e.ownText()的文本,但在这种情况下这还不够,因为你想要单独的This is start of a textand and ending with some text.,但ownText()返回它加入了:This is start of a text and ending with some text.
要获取分隔文本的列表,请使用e.textNodes()body 的输出:

body: [
This is start of a text&nbsp;, and ending with some text.]
a: [followed by a link&nbsp;sample]

另一个好处是你保持原创&nbsp;
此外,如果您不喜欢冗余html: []head: []添加到您的文档中,您应该使用 XML 解析器:

Document document = Jsoup.parse(text, "", Parser.xmlParser());

要保持文本分隔和<a>文本顺序,请尝试使用递归迭代:document.childNodes()然后childNodes()对每个节点进行迭代。您可以通过检查来识别文本节点if (node instanceof TextNode)


推荐阅读