[英]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.