如果包含属性,Jsoup将获得值
问题描述:
我想提取表中specefic标题的值,例如;如果包含属性,Jsoup将获得值
<tr>
<th colspan="8">
<a href="/wiki/Hit_points" title="Hit points" class="mw-redirect">Hit points</a>
</th>
<td colspan="12"> 240</td>
</tr>
<tr>
<th colspan="8"> <a href="/wiki/Aggressive" title="Aggressive" class="mw-redirect">Aggressive</a>
</th><td colspan="12"> Yes
</td></tr>
我希望能够得到的值,例如;
如果标题等于 “命中点” 返回在上述壳体240
。
package test;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class topkek {
public static void main(String[] args) {
try {
Response res = Jsoup.connect("http://2007.runescape.wikia.com/wiki/King_black_dragon").execute();
String html = res.body();
Document doc2 = Jsoup.parseBodyFragment(html);
Element body = doc2.body();
Elements tables = body.getElementsByTag("table");
for (Element table : tables) {
if (table.className().contains("infobox")==true) {
System.out.println(table.getElementsByAttribute("title").text());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答
无需手动去通过文件,你可以简单地使用选择这个:
response
.parse()
.select("th:has(a[title=\"Hit points\"]) ~ td")
.text()
这将选择具有嵌套a
的标题和有兄弟姐妹th
元素td
您可以从中读取内容的元素text()
编辑:如果要列出多个元素,你可以使用这样的事情:
document
.select("th:has(a[title])")
.forEach(e -> {
System.out.println(e.text());
System.out.println(((Element) e.nextSibling()).text());
});