2013-02-13 64 views
1

我試圖使用JSoup從頁面上刮取一些信息,這可以通過一組特定順序的標籤來識別。它們的順序如下:使用JSoup選擇一組標籤

<span class="sold" >Sold</span></td> 
    <td class='prc'> 
     <div class="g-b bidsold" itemprop="price"> 
       AU $1.00</div>    

我期待抓住每一個到位頁面上的AU $ 1.00包裝領域的價值,但他們只能通過跨度類=「賣出選擇來確定, (「span.sold:lt(4)+ [itemprop = price]」),但感覺就像我在黑暗中徘徊一樣!

回答

1

下面的代碼應該做的伎倆!

Document doc = Jsoup.connect(/*URL of your HTML document*/").get(); 
Element part = doc.body(); 
Elements parts = part.getElementsByTag("div"); 
String attValue; 
String requiredContent; 
for(Element ent : parts) 
{ 
    if(ent.hasAttr("class")) 
    { 
     attValue = ent.attr("class"); 
     if(attValue.equals("g-b bidsold")) 
     { 
      System.out.println("\n"); 
      requiredContent=ent.text(); 
      System.out.println(requiredContent); 
     } 
    } 
} 

只要確保迭代並獲取數組中的輸出。

+0

謝謝 - 這就像預期的那樣工作!我可以看到它將所有div標籤作爲元素拉出,然後檢查它們是否具有等於g-b bidold的類,但是它如何選擇前一部分(即class = sold)?只是試圖將我的頭圍繞代碼,以便我可以在必要時在別處重複它! – Edward 2013-02-14 03:27:09

+0

不客氣!我給出的代碼沒有檢查前面的部分。它只是在特定類中尋找div內的內容。如果您還需要檢查span標籤的類,則需要相應地重寫此代碼。 – LGAP 2013-02-15 07:32:51

1

你也可以這樣做:

Elements soldPrices = doc.select("td:has(.sold) + td [itemprop=price]");

這將返回有價元素itemprops(的DIV),已立即與元素(跨度)帶class =賣出前述達陣。

查看Selector syntax瞭解更多詳情。