[英]Using JSoup to parse text between two different tags
我有以下 HTML ...
<h3 class="number">
<span class="navigation">
6:55 <a href="/results/result.html" class="under"><b>»</b></a>
</span>**This is the text I need to parse!**</h3>
我可以使用以下代碼從 h3 標簽中提取文本。
Element h3 = doc.select("h3").get(0);
不幸的是,這給了我該標簽中的所有內容。
6:55 » This is the text I need to parse!
我可以使用 Jsoup 來解析不同的標簽嗎? 是否有這樣做的最佳實踐(正則表達式?)
不,JSoup不是為此而設計的。 它應該解析層次結構。 搜索介於結束標記和開始標記之間的文本,或者相反,對於JSoup來說毫無意義。 這就是正則表達式的用途。
但是,在對字符串進行正則表達式拍攝之前,您當然應該首先使用JSoup將其范圍盡可能縮小。
只需使用 ownText()
@Test
void innerTextCase() {
String sample = "<h3 class=\"number\">\n" +
"<span class=\"navigation\">\n" +
"6:55 <a href=\"/results/result.html\" class=\"under\"><b>»</b></a>\n" +
"</span>**This is the text I need to parse!**</h3>\n";
Assertions.assertEquals("**This is the text I need to parse!**",
Jsoup.parse(sample).select("h3").first().ownText());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.