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类

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

package test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.HTMLElementName;
import au.id.jericho.lib.html.Segment;
import au.id.jericho.lib.html.Source;

/** *//**
 * @author oscar 07-5-17
 * 
 */
public class CourtNews ...{
    private int newsCount = 3;

    private List newsList = new ArrayList();

    public int getNewsCount() ...{
        return newsCount;
    }

    public void setNewsCount(int newsCount) ...{
        this.newsCount = newsCount;
    }

    public List getNewsList() ...{
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(
                "http://www.ahcourt.gov.cn/gb/ahgy_2004/fyxw/index.html");
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());

        try ...{
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) ...{
                System.err
                        .println("Method failed:" + getMethod.getStatusLine());
            }

            String responseBody = getMethod.getResponseBodyAsString();
            responseBody = new String(responseBody.getBytes("ISO-8859-1"),
                    "GB2312");
            Source source = new Source(responseBody);

            int tableCount = 0;

            for (Iterator i = source.findAllElements(HTMLElementName.TABLE)
                    .iterator(); i.hasNext(); tableCount++) ...{

                Segment segment = (Segment) i.next();

                if (tableCount == 13) ...{

                    int hrefCount = 0;
                    for (Iterator j = segment
                            .findAllElements(HTMLElementName.A).iterator(); j
                            .hasNext();) ...{
                        Segment childsegment = (Segment) j.next();
                        String title = childsegment.extractText();
                        title.replace(" ", " ");
                        title = trimTitle(title);
                        Element childelement = (Element) childsegment;
                        if (hrefCount < newsCount) ...{

                            String[] news = new String[] ...{
                                    title,
                                    "http://www.ahcourt.gov.cn"
                                            + childelement
                                                    .getAttributeValue("href") };
                            newsList.add(news);
                            hrefCount++;
                        }
                    }

                }
            }
        } catch (HttpException e) ...{
            System.out.println("please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) ...{
            e.printStackTrace();
        } finally ...{
            getMethod.releaseConnection();
        }
        return newsList;
    }

    private String trimTitle(String title) ...{
        String titlenew = "";

        for (int i = 0; i < title.length(); i++) ...{

            if (Character.isSpaceChar(title.charAt(i)))
                titlenew += " ";
            else ...{
                titlenew += title.charAt(i);
            }

        }
        return titlenew;
    }
    public static void main(String[] args) ...{
        // TODO Auto-generated method stub
        CourtNews justice = new CourtNews();
        justice.setNewsCount(4);
        List list = justice.getNewsList();
        Iterator it = list.iterator();
        while (it.hasNext()) ...{
            String[] news = (String[]) it.next();
            System.out.println(news[0]);
            System.out.println(news[1]);
    }
    }

}

width="490" scrolling="no" height="150" frameborder="0" align="middle" style="width: 490px; height: 150px;" src="http://www.blogbao.com/script.aspx?userid=45735&AdType=0&AdstyleID=46090&Direction=1" marginheight="0" marginwidth="0">

网页爬虫,HttpClient+Jericho HTML Parser 实现网页的抓取相关推荐

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

    //转自:chenqi19831112/archive/2008/11/07/3248863.aspx Jericho HTML Parser是一个简单而功能强大的Java HTML解析器库,可以分析 ...

  2. Python爬虫之XPath基础教程:用代码抓取网页数据

    Python爬虫之XPath基础教程:用代码抓取网页数据 在网络时代,网页数据是获取信息和进行分析的最重要的来源之一.Python的爬虫技术让我们可以轻松抓取网页数据,并进行数据处理.XPath是一种 ...

  3. python爬虫成长之路(一):抓取证券之星的股票数据

    python爬虫成长之路(一):抓取证券之星的股票数据 获取数据是数据分析中必不可少的一部分,而网络爬虫是是获取数据的一个重要渠道之一.鉴于此,我拾起了Python这把利器,开启了网络爬虫之路. 本篇 ...

  4. 【精华】【经典】自动化循环操作方法当前网页方法,可以用于本地化AI智能自动抓取网页资源信息,类似爬虫功能

    第一种:需要刷新当前页面重复执行的操作--使用场景:刷点击率 .秒杀活动.抢沙发 //自动化循环操作方法 var doLoop = function (dom) {dom || (dom = docu ...

  5. 抓取一个连续的网页_搞懂各大搜索引擎蜘蛛的抓取规则,快速获得排名!

    搜索引擎平台的抓取规则: 百度.360.搜狗等搜索引擎抓取规则对比! 蜘蛛抓取规则:深度优先和广度优先 深度优先: 深度优先策略即一条道走到黑,当沿着一个路径走到无路可走时,再返回来走另一条路. 深度 ...

  6. 防止抓取html代码,网页中用html代码注释的内容会被抓取吗

    很多站长都知道网页代码里面有注释代码这么个东西,其形式是 ,在HTML里面注释的内容出现在网页源代码,而用户浏览网页的过程中是看不到的.因为注释内容在源代码展现又不会影响页面内容,所以很多人觉得蜘蛛会 ...

  7. 下面哪个python库不能用于提取网页信息_利用python的webscraping库采集抓取爱帮网电话号码...

    利用python的webscraping模块抓取爱帮网电话号码,本文采集该页面的标题和2个电话号码, 具体的python代码: # -*- coding: UTF-8 -*- ''' Created ...

  8. 如何提取小程序/APP/网页里图片视频,小程序APP素材抓取软件批量下载图片音频?

    通常我们在看到某一个好的小程序素材想下载来参考时?会思考以下问题: "怎么下载别人小程序里的图标呀?" "怎么抓取小程序的图片.图标之类的?" "怎么 ...

  9. 服务器处理蜘蛛抓取网页的过程,让你网站快速被蜘蛛抓取的十三个方法

    据调查显示,有87%的网民会利用搜索引擎服务查找需要的信息,而这之中有近70%的搜索者会直接在搜索结果的自然排名的第一页查找自己所需要的信息.由此可见,目前来讲SEO对于企业和产品,有着难以替代的重要 ...

最新文章

  1. extjs关于jsonreader
  2. linux高性能网络编程读书笔记之socket数据读写
  3. 使用css3的动画模拟太阳系行星公转
  4. 用imageNamed加载图片产生的问题
  5. JVM之XX参数详解
  6. Javascript系列——对象元素的数组去重实现
  7. python控制灯_Python 控制树莓派 GPIO 输出:控制 LED 灯
  8. 最小编辑代价-golang
  9. java的foreach_深入理解java中for和foreach循环
  10. Python按元组中第一个字符串升序第二个字符串降序排序
  11. FFmpeg学习3:播放音频
  12. Mac硬件温度管理软件TG Pro
  13. 发票验证出现服务器证书出错,网上认证发票平台证书密码出现错误怎么办?
  14. 超震撼数据可视化工具
  15. 德清租房软件测试,张家口商场附近出租房
  16. php业名人,名人榜
  17. UIkit框架之轮播特效
  18. fatal: unsafe repository is owned by someone else 的解决方法
  19. 【剑指offer】面试题46:把数字翻译成字符串【C++版本】
  20. python与spider的区别_python – Scraw spider与Scraped items之间的区别

热门文章

  1. .NET中Redis安装部署及使用方法
  2. Codeforces Beta Round #97 (Div. 1) C. Zero-One 数学
  3. attribute property --- jquery attr() prop()
  4. 【MaxScript】删除所选择的骨骼的位置和缩放
  5. SQL CASE 的用法
  6. WPF中MVVM模式(简略介绍)
  7. mysql 8创建远程访问用户以及连接mysql速度慢的解决方法
  8. Confluence5.8部分空间名称显示为问号的解决方案
  9. 解决mac下ssh空闲一段时间自动断开的问题
  10. 使用Thumbnailator处理gif图片时遇到java.lang.ArrayIndexOutOfBoundsException: 4096异常处理