从 jsoup 中的许多 <p> 标签解析单个 <p> 标签
Parsing a single <p> tag from many <p> tag in jsoup
我想打印来自 <p>I want only this line</p>
tag 的行并忽略所有其他行。
我关注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()
那么你只需要检查返回的元素是否不为空。否则,您可以获得 NullPointException。
我想打印来自 <p>I want only this line</p>
tag 的行并忽略所有其他行。
我关注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()
那么你只需要检查返回的元素是否不为空。否则,您可以获得 NullPointException。