HttpClient+Jericho HTML Parser 实现网页的抓取

Jericho HTML Parser是一个简单而功能强大的Java HTML解析器库,可以分析和处理HTML文档的一部分,包括一些通用的服务器端标签,同时也可以重新生成无法识别的或无效的HTML。它也提供了一个有用的HTML表单分析器。
  下载地址:http://sourceforge.net/project/showfiles.php?group_id=101067

  HttpClient作为HTTP客户端组件与服务器进行通讯,同时使用了jdom进行XML数据的解析。

    * HttpClient 可以在http://jakarta.apache.org/commons/httpclient/downloads.html下载
    * HttpClient 用到了 Apache Jakarta common 下的子项目 logging,你可以从这个地址http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi下载到 common logging,从下载后的压缩包中取出 commons-logging.jar 加到 CLASSPATH 中
    * HttpClient 用到了 Apache Jakarta common 下的子项目 codec,你可以从这个地址http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi 下载到最新的 common codec,从下载后的压缩包中取出 commons-codec-1.x.jar 加到 CLASSPATH 中


在对网页信息进行抓取时,主要会用到GET 方法

使用 HttpClient 需要以下 6 个步骤:

1. 创建 HttpClient 的实例

2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址

3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

4. 读 response

5. 释放连接。无论执行方法是否成功,都必须释放连接

6. 对得到后的内容进行处理
在eclipse下建立工程 -->snatch
将上面下载的四个jar文件导入到项目路径中.
环境搭建完成

现在,首先介绍一下HttpClient的使用
在工程目录下创建test包,在包中创建Httpclient Test类

Java代码 复制代码  收藏代码
  1. package test;  
  2. import java.io.IOException;  
  3. import org.apache.commons.httpclient.*;  
  4. import org.apache.commons.httpclient.methods.GetMethod;  
  5. import org.apache.commons.httpclient.params.HttpMethodParams;  
  6. public class HttpClientTest...{  
  7.   public static void main(String[] args) {  
  8.   //构造HttpClient的实例  
  9.   HttpClient httpClient = new HttpClient();  
  10.   //创建GET方法的实例  
  11.   GetMethod getMethod = new GetMethod("http://www.google.com.cn");  
  12.   //使用系统提供的默认的恢复策略  
  13.   getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
  14.     new DefaultHttpMethodRetryHandler());  
  15.   try {  
  16.    //执行getMethod  
  17.    int statusCode = httpClient.executeMethod(getMethod);  
  18.    if (statusCode != HttpStatus.SC_OK) {  
  19.     System.err.println("Method failed: "  
  20.       + getMethod.getStatusLine());  
  21.    }  
  22.    //读取内容   
  23.    byte[] responseBody = getMethod.getResponseBoy();  
  24.    //处理内容  
  25.    System.out.println(new String(responseBody));  
  26.   } catch (HttpException e) {  
  27.    //发生致命的异常,可能是协议不对或者返回的内容有问题  
  28.    System.out.println("Please check your provided http address!");  
  29.    e.printStackTrace();  
  30.   } catch (IOException e) {  
  31.    //发生网络异常  
  32.    e.printStackTrace();  
  33.   } finally {  
  34.    //释放连接  
  35.    getMethod.releaseConnection();  
  36.   }  
  37.  }  
  38. }  
package test;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientTest...{
  public static void main(String[] args) {
  //构造HttpClient的实例
  HttpClient httpClient = new HttpClient();
  //创建GET方法的实例
  GetMethod getMethod = new GetMethod("http://www.google.com.cn");
  //使用系统提供的默认的恢复策略
  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler());
  try {
   //执行getMethod
   int statusCode = httpClient.executeMethod(getMethod);
   if (statusCode != HttpStatus.SC_OK) {
    System.err.println("Method failed: "
      + getMethod.getStatusLine());
   }
   //读取内容 
   byte[] responseBody = getMethod.getResponseBoy();
   //处理内容
   System.out.println(new String(responseBody));
  } catch (HttpException e) {
   //发生致命的异常,可能是协议不对或者返回的内容有问题
   System.out.println("Please check your provided http address!");
   e.printStackTrace();
  } catch (IOException e) {
   //发生网络异常
   e.printStackTrace();
  } finally {
   //释放连接
   getMethod.releaseConnection();
  }
 }
}



这样得到的是页面的源代码.
这里 byte[] responseBody = getMethod.getResponseBoy();是读取内容
除此之外,我们还可以这样读取:
InputStream inputStream=   getMethod.getResponseBodyAsStream();
String responseBody = getMethod.getResponseBodyAsString();


下面结合两者给个事例
取出http://www.ahcourt.gov.cn/gb/ahgy_2004/fyxw/index.html
中"信息快递"栏的前几条信息.
新建类CourtNews

Java代码 复制代码  收藏代码
  1. package test;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7.   
  8. import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
  9. import org.apache.commons.httpclient.HttpClient;  
  10. import org.apache.commons.httpclient.HttpException;  
  11. import org.apache.commons.httpclient.HttpStatus;  
  12. import org.apache.commons.httpclient.methods.GetMethod;  
  13. import org.apache.commons.httpclient.params.HttpMethodParams;  
  14.   
  15. import au.id.jericho.lib.html.Element;  
  16. import au.id.jericho.lib.html.HTMLElementName;  
  17. import au.id.jericho.lib.html.Segment;  
  18. import au.id.jericho.lib.html.Source;  
  19.   
  20. /** *//** 
  21.  * @author oscar 07-5-17 
  22.  *  
  23.  */  
  24. public class CourtNews {  
  25.     private int newsCount = 3;  
  26.   
  27.     private List newsList = new ArrayList();  
  28.   
  29.     public int getNewsCount() {  
  30.         return newsCount;  
  31.     }  
  32.   
  33.     public void setNewsCount(int newsCount) {  
  34.         this.newsCount = newsCount;  
  35.     }  
  36.   
  37.     public List getNewsList() {  
  38.         HttpClient httpClient = new HttpClient();  
  39.         GetMethod getMethod = new GetMethod(  
  40.                 "http://www.ahcourt.gov.cn/gb/ahgy_2004/fyxw/index.html");  
  41.         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
  42.                 new DefaultHttpMethodRetryHandler());  
  43.   
  44.         try {  
  45.             int statusCode = httpClient.executeMethod(getMethod);  
  46.             if (statusCode != HttpStatus.SC_OK) {  
  47.                 System.err  
  48.                         .println("Method failed:" + getMethod.getStatusLine());  
  49.             }  
  50.   
  51.             String responseBody = getMethod.getResponseBodyAsString();  
  52.             responseBody = new String(responseBody.getBytes("ISO-8859-1"),  
  53.                     "GB2312");  
  54.             Source source = new Source(responseBody);  
  55.   
  56.             int tableCount = 0;  
  57.   
  58.             for (Iterator i = source.findAllElements(HTMLElementName.TABLE)  
  59.                     .iterator(); i.hasNext(); tableCount++) {  
  60.   
  61.                 Segment segment = (Segment) i.next();  
  62.   
  63.                 if (tableCount == 13) {  
  64.   
  65.                     int hrefCount = 0;  
  66.                     for (Iterator j = segment  
  67.                             .findAllElements(HTMLElementName.A).iterator(); j  
  68.                             .hasNext();) {  
  69.                         Segment childsegment = (Segment) j.next();  
  70.                         String title = childsegment.extractText();  
  71.                         title.replace(" "" ");  
  72.                         title = trimTitle(title);  
  73.                         Element childelement = (Element) childsegment;  
  74.                         if (hrefCount < newsCount) {  
  75.   
  76.                             String[] news = new String[] {  
  77.                                     title,  
  78.                                     "http://www.ahcourt.gov.cn"  
  79.                                             + childelement  
  80.                                                     .getAttributeValue("href") };  
  81.                             newsList.add(news);  
  82.                             hrefCount++;  
  83.                         }  
  84.                     }  
  85.   
  86.                 }  
  87.             }  
  88.         } catch (HttpException e) {  
  89.             System.out.println("please check your provided http address!");  
  90.             e.printStackTrace();  
  91.         } catch (IOException e) {  
  92.             e.printStackTrace();  
  93.         } finally {  
  94.             getMethod.releaseConnection();  
  95.         }  
  96.         return newsList;  
  97.     }  
  98.   
  99.     private String trimTitle(String title) {  
  100.         String titlenew = "";  
  101.   
  102.         for (int i = 0; i < title.length(); i++) {  
  103.   
  104.             if (Character.isSpaceChar(title.charAt(i)))  
  105.                 titlenew += " ";  
  106.             else {  
  107.                 titlenew += title.charAt(i);  
  108.             }  
  109.   
  110.         }  
  111.         return titlenew;  
  112.     }  
  113.     public static void main(String[] args) {  
  114.         // TODO Auto-generated method stub  
  115.         CourtNews justice = new CourtNews();  
  116.         justice.setNewsCount(4);  
  117.         List list = justice.getNewsList();  
  118.         Iterator it = list.iterator();  
  119.         while (it.hasNext()) {  
  120.             String[] news = (String[]) it.next();  
  121.             System.out.println(news[0]);  
  122.             System.out.println(news[1]);  
  123.     }  
  124.     }  
  125.   
  126. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值