【问题标题】:Parse HTML to get text for individual elements using Jsoup使用 Jsoup 解析 HTML 以获取单个元素的文本
【发布时间】:2020-02-22 06:24:25
【问题描述】:

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

正文是:

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.

【问题讨论】:

    标签: jsoup html-parsing


    【解决方案1】:

    为避免返回所有子项的文本,请使用 e.ownText(),但在这种情况下这还不够,因为您希望将 This is start of a textand 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]
    

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

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

    要保持文本分隔和&lt;a&gt; 文本,以尝试递归迭代使用:document.childNodes(),然后childNodes() 用于每个节点。您可以通过检查if (node instanceof TextNode)来识别文本节点。

    【讨论】:

    • 感谢您的帮助!!
    猜你喜欢
    • 2016-04-18
    • 1970-01-01
    • 2015-01-03
    • 2016-08-13
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多