提取HTML标记之外的文本

时间:2013-11-09 22:09:13

标签: java android html jsoup

我有以下HTML代码:

<div class=example>Text #1</div> "Another Text 1"
<div class=example>Text #2</div> "Another Text 2"

我想提取标签外的文字,“另一个文字1”和“另一个文字2”

我正在使用JSoup来实现这一目标。

任何想法???

谢谢!

2 个答案:

答案 0 :(得分:4)

一种解决方案是使用ownText()方法(请参阅Jsoup docs)。此方法仅返回指定元素所拥有的文本,并忽略其直接子元素所拥有的任何文本。

仅使用您提供的html,您可以提取<body> owntext:

String html = "<div class='example'>Text #1</div> 'Another Text 1'<div class='example'>Text #2</div> 'Another Text 2'";

Document doc = Jsoup.parse(html);
System.out.println(doc.body().ownText());

将输出:

'Another Text 1' 'Another Text 2'

请注意,ownText()方法可用于任何Elementdocs中有另一个例子。

答案 1 :(得分:2)

您可以选择每个Node标记的下一个Element(不是div!)。在您的示例中,它们都是TextNode

final String html = "<div class=example>Text #1</div> \"Another Text 1\"\n"
                  + "<div class=example>Text #2</div> \"Another Text 2\" ";

Document doc = Jsoup.parse(html);

for( Element element : doc.select("div.example") ) // Select all the div tags
{
    TextNode next = (TextNode) element.nextSibling(); // Get the next node of each div as a TextNode

    System.out.println(next.text()); // Print the text of the TextNode
}

输出:

 "Another Text 1" 
 "Another Text 2" 
相关问题