httpClient获取Jsoup解析网页

因项目需要从某个网站爬取一点数据,故我将爬取记录如下,以后说不定还能用得到呢,废话少说,进入正题:

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 HTTPClient,然后根据作者实际工作经验给出了一些常见问题的解决方法。

HttpClient 主页:http://hc.apache.org/httpcomponents-client-dev/index.html

jsoup是一个Java HTML Parser。能够从URL、文件或字符串解析HTML。利用DOM遍历或CSS选择器查找和抽取数据。能够操作HTML元素,属性和文本。能够依据一个白名单过滤用户提交的内容。

jsoup主页:http://jsoup.org/

具体的我就不解释了 自己度娘、谷哥去

要不找个例子先?!

比如就拿www.iteye.com首页来说吧,我想定时抓取iteye首页“精华文章”里面的数据

思路,用代码请求www.iteye.com首页,拿到首页的html代码,解析html代码,获取“精华文章”里面文章的连接地址在此请求该地址,拿下该文章,是吧?!ok,来看处理过程:

 先用浏览器打开www.iteye.com,可以用调试工具 firefox装上firebug chrome右击审核元素

以firefox为例:


可以发现“精华文章” 里面文章的全结构是

在id=“page”的div下面的 

   id=“content”的div下面的 

   id=“main”的div下面的

   class=“left”的div下面的

   id=“recommend”的div下面的

   ul下面的li下面的a标签

首先用httpClient获取首页html代码 我用的是httpClient4.1.2  jar包见附件 jsoup用的是jsoup-1.6.1.jar

/**
	 * 根据URL获得所有的html信息
	 * @param url
	 * @return
	 */
	public static String getHtmlByUrl(String url){
		String html = null;
		HttpClient httpClient = new DefaultHttpClient();//创建httpClient对象
		HttpGet httpget = new HttpGet(url);//以get方式请求该URL
		try {
			HttpResponse responce = httpClient.execute(httpget);//得到responce对象
			int resStatu = responce.getStatusLine().getStatusCode();//返回码
			if (resStatu==HttpStatus.SC_OK) {//200正常  其他就不对
				//获得相应实体
				HttpEntity entity = responce.getEntity();
				if (entity!=null) {
					html = EntityUtils.toString(entity);//获得html源代码
				}
			}
		} catch (Exception e) {
			System.out.println("访问【"+url+"】出现异常!");
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return html;
	}

上面是用httpClient获取html源文件的代码

下面就是对该html页面进行解析 得到我们想要的连接

 下面是jsoup处理得到的html源码

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JustTest {
	public static void main(String[] args) {
		String html = getHtmlByUrl("http://www.iteye.com/");
		if (html!=null&&!"".equals(html)) {
			Document doc = Jsoup.parse(html);
			Elements linksElements = doc.select("div#page>div#content>div#main>div.left>div#recommend>ul>li>a");
			//以上代码的意思是 找id为“page”的div里面   id为“content”的div里面   id为“main”的div里面   class为“left”的div里面   id为“recommend”的div里面ul里面li里面a标签
			for (Element ele:linksElements) {
				String href = ele.attr("href");
				String title = ele.text();
				System.out.println(href+","+title);
			}
		}
	}
}
 

其实jsoup的语法很简单,就是跟jquery一样用“#”取id,用“.”取样式位之后的数据 

其实都很简单的,当然,越规范的网页分析起来越容易,要是网页不规范就只好大家多写点代码咯

贴上Jsoup的API:http://jsoup.org/apidocs/

猜你喜欢

转载自ducaijun.iteye.com/blog/1335453