2017-02-11 58 views
0

我的問題是:如何搜索用Jsoup選擇的頁面中的單詞或短語。
例如,如果在一個範圍中的單詞或短語我怎麼能找到每個例子<span>旁邊的文本?例如一個鏈接?Android:如何用Jsoup搜索單詞或短語

的Html代碼示例:

... 
    <div class="div"> 
    <span>my y favourite text </span> 
    <a href="www.mylink.com">my link </a> 
    </div> 
    .... 

從這個例子中如何找到我的話是最喜歡的,我也想檢索<a href>的聯繫?

+0

http://stackoverflow.com/q/8451801/7012517參考此鏈接..! – Shobhit

+0

謝謝......我讀過,但我不明白他在做什麼:( – 24terminator96

+0

@shobhit你有其他的選擇嗎? – 24terminator96

回答

2

目標:獲取spanhref中的文本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 
+0

在doc.select〜是相同的>? – 24terminator96

+0

是一樣的simbol? – 24terminator96

+0

不,是爲孩子,〜爲兄弟姐妹。請參閱:http://www.w3schools.com/css /css_combinators.asp –