2012-09-15 22 views
1

超鏈接我有Jsoup正從李

<div id = top1> 
    <div id topsub1> 
    <ul class="student"> 
    <li> 
    <a href="/thomas">Tom</a> 
    </li> 
    </div> 
    <div id topsub2> 
    <ul class="student"> 
    <li> 
    <a href="/thomas1">Tom1</a> 
    </li> 
    </div> 
</div> 

我想要得到的href和文本 所以我做 元素XX =選擇(DIV DIV UL LI)

當我做的foreach XX爲y,如果我做

string1 = y.text(); //這是打印Tom String2 = y.attr(「href」)//這總是空的。我無法得到/托馬斯? 我也試過y.attr(「a [href]」))

還有什麼是: doc.select(「。studentnames> a」);? 這是否意味着在ID = studentnames上獲得所有的「a」正確?

+0

您的html代碼看起來與裸體的div搞砸了。考慮編輯這個並重新發布更有意義,更容易理解的html代碼。 –

+0

感謝您的回覆我更新了 –

回答

2

如果你只是做了Elements eles = doc.select("a[href]");?另外我相信,當使用attrib(...)方法時,您不會傳入標籤,只是屬性名稱本身。

編輯:
幽州:

然後修正結果通過順序調用多個選擇或鏈接他們返回你的選擇:

Elements eles = doc.select("ul.student").select("a[href]"); 

或者也許(我從來沒有這樣做):

Elements eles = doc.select("ul.student a[href]"); 

或甚至:

Elements eles = doc.select("div > div > ul.student > li > a[href]"); 
+0

與做doc.select(「a [href] ..的問題..有許多屬性和hrefs ..我只想這是旁邊的學生名字..這就是爲什麼我立即做後我做文本,以便我可以得到 - 學生的姓名和他的網站 –

+0

@ TheLearner:請看最新的編輯。 –

0

這是你的錯誤:

你的第一選擇只得到div div ul li,使Elements只包含li標籤(一個或多個)。所以,你可以做以下的方法之一:

獲取每個元素

for (Element x: yy) { 
    Element aTag = x.child(0); 
    // or it can be aTag = x.select("a[href]").first(); 
    // Do your stuff here ! 
} 

從選擇查詢獲取:

Elements yy = doc.select("div div ul li a[href]"); 

我想提一提的是,請不要使用Element.text()是要獲取標籤內的數據,所以在這種情況下,它是li。在調試時,您應該使用Element.html()Elements.html()

2.關於您的關注:

and also what is : doc.select(".studentnames > a") ? does this mean that on the ID=studentnames get all the "a" correct???

.是一流的,而#爲id。 此外,>直接子

所以您的查詢是指:「返回所有的一個標籤,它是一個直接孩子擁有類等於‘studentnames’標籤的」

對於更具體的瞭解,你應該檢查Jsoup's Selector's document