原文地址:http://qzone.qq.com/blog/22340638-1212662447

htmlparser使用举例
HTMLParser 一个解析web页面的开源类库, 他有两种主要使用方式, extraction和transformation. 前者就是从网页中萃取出你要的东西,后者就是把web页面中的一些内容改为(转换为)你想要的格式. 下面来看看这两种使用情况的各自特点.
Extraction
萃取例如下面的几种常见的使用方式:
    * text extraction, 萃取web页面中的文本文字
    * link extraction,萃取web页面中的连接 包括url 和 email地址, 还可以自定义其他标签
    * screen scraping, 抓去web页面内容
    * resource extraction, 萃取web页面中的资源, 图片 , 声音文件......
    * a browser front end, the preliminary stage of page display
    * link checking, 确保连接是有效的
    * site monitoring, 检查web页面的更改
使用一下几种机制来帮助你实现上面的功能:
filters, visitors and JavaBeans
Transformation
处理web页面的内容, 转换为你需要的.包含:
    * URL rewriting, 更改一个web页面的部分连接or 全部连接为你想要的.
    * site capture, 把远程的网站抓取到本地
    * censorship, 检查web页面内容,移出你不想要的字词
    * HTML cleanup, 整理html格式,
    * ad removal, 过滤广告连接
    * conversion to XML, 转换为xml格式的数据
另外: htmlparser还使用到了几种很好的设计模式.应用的恰到好处, 值得学习和借鉴一下.
这次对htmlparser的简单介绍先介绍到这里, 在以后的时间里 根据具体的应用在写一些例子, 给大家参考一下(htmlparser源代码中也有几个例子,建议看看).  

下面通过一个简单的htmlparser的使用举例,来学习htmlparser的使用。代码如下:

package com.amigo.htmlparser;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import org.htmlparser.filters.*;
import org.htmlparser.*;
import org.htmlparser.nodes.*;
import org.htmlparser.tags.*;
import org.htmlparser.util.*;
import org.htmlparser.visitors.*;
/** *//**
* 测试HTMLParser的使用.
* @author <a href="liuqlmailto:liuql-ja@163.com">liuql</a>
* Creation date: 2008-6-5 - 上午11:44:22
*/

public class HTMLParserTest {
        /** *//**
         * 入口方法.
         * @param args
         * @throws Exception
         */

        public static void main(String args[]) throws Exception {
                String path = "http://www.163.com";
                URL url = new URL(path);
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                
                InputStream inputStream = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(inputStream, "utf8");
                StringBuffer sb = new StringBuffer();
                BufferedReader in = new BufferedReader(isr);
                String inputLine;
                
                while ((inputLine = in.readLine()) != null) {
                        sb.append(inputLine);
                        sb.append("\n");
                }
                
                String result = sb.toString();
                readByHtml(result);
                readTextAndLinkAndTitle(result);
        }
        
        /** *//**
         * 按页面方式处理.解析标准的html页面
         * @param content 网页的内容
         * @throws Exception
         */

        public static void readByHtml(String content) throws Exception {
                Parser myParser;
                myParser = Parser.createParser(content, "utf8");
                HtmlPage visitor = new HtmlPage(myParser);
                myParser.visitAllNodesWith(visitor);
                String textInPage = visitor.getTitle();
                System.out.println(textInPage);
                NodeList nodelist;
                nodelist = visitor.getBody();
                
                System.out.print(nodelist.asString().trim());
        }
        /** *//**
         * 分别读纯文本和链接.
         * @param result 网页的内容
         * @throws Exception
         */

        public static void readTextAndLinkAndTitle(String result) throws Exception {
                Parser parser;
                NodeList nodelist;
                parser = Parser.createParser(result, "utf8");
                NodeFilter textFilter = new NodeClassFilter(TextNode.class);
                NodeFilter linkFilter = new NodeClassFilter(LinkTag.class);
                NodeFilter titleFilter = new NodeClassFilter(TitleTag.class);
                OrFilter lastFilter = new OrFilter();
                lastFilter.setPredicates(new NodeFilter[] { textFilter, linkFilter, titleFilter });
                nodelist = parser.parse(lastFilter);
                Node[] nodes = nodelist.toNodeArray();
                String line = "";
                
                for (int i = 0; i < nodes.length; i++) {
                        Node node = nodes;
                        if (node instanceof TextNode) {
                                TextNode textnode = (TextNode) node;
                                line = textnode.getText();
                        } else if (node instanceof LinkTag) {
                                LinkTag link = (LinkTag) node;
                                line = link.getLink();
                        } else if (node instanceof TitleTag) {
                                TitleTag titlenode = (TitleTag) node;
                                line = titlenode.getTitle();
                        }
                        
                        if (isTrimEmpty(line))
                                continue;
                        System.out.println(line);
                }
        }
        
        /** *//**
         * 去掉左右空格后字符串是否为空
         */

        public static boolean isTrimEmpty(String astr) {
                if ((null == astr) || (astr.length() == 0)) {
                        return true;
                }
                if (isBlank(astr.trim())) {
                        return true;
                }
                return false;
        }
        /** *//**
         * 字符串是否为空:null或者长度为0.
         */

        public static boolean isBlank(String astr) {
                if ((null == astr) || (astr.length() == 0)) {
                        return true;
                } else {
                        return false;
                }
        }
}