我想从<p>I want only this line</p>
标记中打印该行,并希望忽略所有其他行。
我有以下html:
<div class="my value">
<h2>Head2</h2>
<p> </p>
<p><strong></strong>Date</p>
<p></p>
<h2><u>Head2</u></h2>
<p> </p>
<p>I want only this line</p>
<p> </p>
<p><strong><u></u></strong></p>
<p> </p>
<p>I do not want this line</p>
</div>
而我的Java代码是:
String html = "link of the website that contains my html I have showed on top";
Document doc;
try {
doc = Jsoup.connect(html).get();
Elements link = doc.select("div.my.value");
doc=Jsoup.parse(link.html());
link =doc.select("p");
String linkText = link.text();
System.out.println("Link Text\n" + linkText);
} catch (IOException ex) {
System.out.println("err: " + ex);
}
输出为:
我只想要这条线我不要这条线
但是我只想打印这一行,我只想打印此行,并且想忽略所有其他<p> </p>
标签。我怎样才能做到这一点?
获得所需内容的关键是创建一个好的选择器。让我们来看一些使用HTML的示例:
1)按内容选择:p:contains(I want only this line)
或者,如果您想更具体一点,div.my p:contains(I want only this line)
2)通过DOM中的位置进行选择: div p:eq(6)
为了获取元素,我更喜欢使用以下语句: Jsoup.parse(html).select("div.my p:contains(I want only this line)").first()
然后,您只需要检查返回的元素是否不为null。否则,您将获得NullPointException。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句