2014-02-07 29 views
0

我正在使用jsoup解析一個html頁面。這裏是我做了什麼至今:如何獲得jsoup鏈接中的文本?

doc = Jsoup.connect("http://www.marketimyilmazlar.com/index.php?route=product/category&path=141_77").get(); 

Element page_clips = doc.getElementById("page_clips"); 

Element page_clip_content = page_clips.getElementById("content"); 
Elements allProductPricesOnPage = page_clip_content.getElementsByClass("price"); 

現在,當我寫:

allProductNamesOnPage.get(0); 

返回我下面的:

<div class="name"> 
<a href="http://www.marketimyilmazlar.com/index.php? 
route=product/product&amp;path=141_77&amp;product_id=4309"> here is the text</a> 
</div> 

我想要做的是,我想獲取該對象的「這裏是文本」部分。任何人都可以幫助我嗎?

感謝

回答

1

您可能要遍歷Elements你有收集並打印他們的價格一一:

Elements allProductPricesOnPage = page_clip_content 
       .getElementsByClass("price"); 
for (Element el : allProductPricesOnPage) { 
    System.out.println(el.text()); 
} 

給人,

19.99 TL KDV Dahil 
9.99 TL KDV Dahil 
14.99 TL KDV Dahil 

它是做什麼的,你選擇Elements其實施Iterator(見javadoc here),它可以讓你訪問您的集合中的個人Element對象。

這些Element中的每一個在您的HTML中重複的對象都有您想要提取的相關信息。

1

如果你想只提取文本,你可以調用text()方法:

String text = allProductNamesOnPage.get(0).text(); 

這種方法獲取元素及其結合孩子們的文字。所以,如果你想確保你只從一個元素中提取文本,調用text()第一個子元素:

String text = allProductNamesOnPage.get(0).child(0).text(); 

在這裏看到:http://jsoup.org/cookbook/extracting-data/attributes-text-html