标签:
这两天弄了一下jsoup 感觉蛮好弄的,这里就分享一下
用到的jar包是 jsoup-1.8.1.jar 可以去官网下载,我用的是目前最新的版本,我获取的以下的网址
这是一个新闻网站,内容比较好获取,也更新得快http://www.xinhuanet.com/xhjj.htm
这里需要说明一下,并没有其他用途,只是用来学习 jsoup
接下来看代码
static String url="http://www.xinhuanet.com/xhjj.htm";
/**
* 获取指定HTML 文档指定的body
* @throws IOException
*/
static List<News> list;
public static void main(String[] args) throws Exception {
BolgBody();
}
public static List<News> BolgBody() throws IOException {
list =new ArrayList<News>();
// 从 URL 直接加载 HTML 文档
Document doc2 = Jsoup.connect(url).get();
//
Elements masthead = doc2.select("div#hideData");
for (Element item : masthead) {
Elements links = item.select("ul");
Elements link = item.select("li");
Elements link1 = item.select("a");
//时间需要改变,因为一行有两个标题
Elements link2 = item.select("span");
// 这里只获取三条
for(int i=0;i<3;i++){
News news = new News();
news.setTitle(link1.get(i).text());
news.setDate(link2.get(i%2).text());//一条记录有两条标题
list.add(news);
}
System.out.println(list.toString());
}
return list;
}
以上是获取时间和标题 注释有
看效果

抓取的时候需要根据网页中的代码来改变
标签:
原文地址:http://www.cnblogs.com/Striver-zw/p/4197177.html