[英]How to add a <br> after a div that contains a specific value for an attribute with JSoup
[英]Jsoup get value if contains attribute
我想提取表中特定标题的值,例如;
<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()
这将选择一个th
元素,该元素具有带有标题的嵌套a
并且具有一个兄弟td
元素,您可以使用text()
从中读取内容
编辑:如果你想列出多个元素,你可以使用这样的东西:
document
.select("th:has(a[title])")
.forEach(e -> {
System.out.println(e.text());
System.out.println(((Element) e.nextSibling()).text());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.