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()
总结下:使用这个框架可以很轻松的从网页中爬取想要的标签获得属性的值。