Jsoup是爬取網頁html數據的一個框架 使用起來也是很簡單的 基本上稍微懂點html使用起來就不會有什麼問題了
使用步驟:
1.獲得html的Document對象 這裏只需要注意需要將timeout設置的稍微長點 因爲Jsoup默認超時時間很短不設置下經常出現超時異常
/**
* 獲得Document對象
* @param host
* @param url
* @return
*/
public static Document getDoucument(String host, String url) {
Document doc = null;
try {
String fullurl = host + url;
System.out.println(fullurl);
doc = Jsoup.connect(fullurl).timeout(30000).post();
} catch (Exception exception) {
log.e(exception);
Thread.currentThread().interrupt();
return doc;
}
return doc;
}
2.獲得想要的標籤Elements 我已"td"標籤爲例,使用起來很像js 有很多獲得的方法可以自己嘗試 獲得Document對象後打個"."代碼提示看下Document方法的名字 基本上就是到該怎麼用了。
/**
* 獲得TD的Elements對象
* @param host
* @param url
* @return
* @throws SocketException
*/
public static Elements getTdElements(String host, String url) {
Document doc = getDoucument(host, url);
if(doc==null){
return null;
}
return doc.getElementsByTag("td");
}
3.獲得標籤的屬性的value:
td.attr(attributeKey) 通過該方法直接就後的了該標籤Element屬性的Element的value值
4.獲得標籤的父標籤:
td.parent()
總結下:使用這個框架可以很輕鬆的從網頁中爬取想要的標籤獲得屬性的值。