目標:獲取span
和href
中的文本a
元素的屬性,如果span
包含指定的搜索詞。
一種方法是尋找具有href
屬性集,具有preceding siblingspan
元素的a
。然後選擇父元素並在其中選擇span
元素以比較內容。對於DOM樹的解析,jsoup是一個不錯的選擇。
示例代碼
String source = "<div class=\"div\"><span>my y favourite text </span><a href=\"http://www.mylink.com\">my link </a></div>" +
"<div class=\"div\"><span>my y favourite 2 text </span><a href=\"/some-link.html\">my link 1</a></div>" +
"<div class=\"div\"><span>my y text </span><a href=\"http://www.mylink.com\">my link 2</a></div>";
String searchWord = "favourite";
Document doc = Jsoup.parse(source, "UTF-8");
doc.setBaseUri("http://some-source.com"); // only for absolute links in local example
Element parent;
String spanContent="";
String link = "";
for (Element el : doc.select("span ~ a[href]")) {
parent = el.parent();
if(parent.select("span").text().contains(searchWord)){
spanContent = parent.select("span").first().text();
link = parent.select("a[href]").first().absUrl("href");
System.out.println(spanContent + " -> " + link); // do something useful with the matches
}
}
輸出
my y favourite text -> http://www.mylink.com
my y favourite 2 text -> http://some-source.com/some-link.html
http://stackoverflow.com/q/8451801/7012517參考此鏈接..! – Shobhit
謝謝......我讀過,但我不明白他在做什麼:( – 24terminator96
@shobhit你有其他的選擇嗎? – 24terminator96