我有以下的HTML代码:提取文本
<div class=example>Text #1</div> "Another Text 1"
<div class=example>Text #2</div> "Another Text 2"
我想提取以外的标记文本,“另一个文本1”和“其他文本2”
我使用JSoup来实现这一点。
任何想法???
谢谢!
我有以下的HTML代码:提取文本
<div class=example>Text #1</div> "Another Text 1"
<div class=example>Text #2</div> "Another Text 2"
我想提取以外的标记文本,“另一个文本1”和“其他文本2”
我使用JSoup来实现这一点。
任何想法???
谢谢!
您可以选择每个div
-tag的下一个Node
(不是Element
!)。在你的例子中,他们都是TextNode
's。
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"
一个解决方案是使用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()
方法可以在任何Element
使用。 docs还有另一个例子。
非常感谢! – johnny243