[英]how to get message in Jsoup for a specific tag only in java?
我的HTML中有這樣的標簽:
<p class="outter">
<strong class="inner">not needed message</strong>
NEEDED MESSAGE
</p>
我正在嘗試提取“需要的消息”
但是如果我做這樣的事情:
String results = document.select("p.outter").text();
System.out.println(results);
它打印:
不需要的消息需要的消息
所以問題是:
如何獲取特定標簽的文本, 而沒有其內部標簽的文本?
一種解決方案是僅選擇TextNode
元素。 在下面找到一個小片段。
String html = "<p class=\"outter\">\n"
+ " <strong class=\"inner\">not needed message</strong>\n"
+ " NEEDED MESSAGE\n"
+ "</p>";
Document doc = Jsoup.parse(html);
Elements elements = doc.select("p.outter");
for (Element element : elements) {
// as mentioned by luksch
System.out.println("ownText = " + element.ownText());
// or manually based on the node type
for (Node node : element.childNodes()) {
if (node instanceof TextNode) {
System.out.println("node = " + node);
}
}
}
產量
node =
node = NEEDED MESSAGE
因此,您需要根據需要過濾輸出。 例如跳過空的。
您可以在選擇段落之后使用ownText()
。 例
package com.stackoverflow.answer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.jsoup.nodes.Element;
public class HtmlParserExample {
public static void main(String[] args) {
String html = "<p class=\"outter\"><strong class=\"inner\">not needed message</strong>NEEDED MESSAGE</p>";
Document doc = Jsoup.parse(html);
Elements paragraphs = doc.select("p");
for (Element p : paragraphs)
System.out.println(p.ownText());
}
}
使用Jsoup的ownText ()方法:
String results = document.select("p.outter").ownText();
System.out.println(results);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.