NekoHTML学习笔记 (zhuan)

NekoHTML学习笔记

  J. Andrew ClarkJava写了一系列的工具(Java APIs)NekoHTML是其中之一。
  NekoHTML是一个简单地HTML扫描器和标签补偿器(tag balancer) ,使得程序能解析HTML文档并用标准的XML接口来访问其中的信息。这个解析器能投扫描HTML文件并"修正"许多作者(人或机器)在编写HTML文档过程中常犯的错误。NekoHTML能增补缺失的父元素、自动用结束标签关闭相应的元素,以及不匹配的内嵌元素标签。NekoHTML的开发使用了Xerces Native Interface (XNI),后者是Xerces2的实现基础。

  

一、运行要求

  从NekoHTML主页上下载nekohtml-latest.zip,目前版本是0.8.
  NekoHTML要求运行在java1.1或更高版本,Xerces-J 2.0或更高版本。(我在试用时,随便拿了个xerces的包来用,结果例如运行老时不能通过,折腾半天后才发现版本不够所致.:)
  

二、使用NekoHTML


1
、透明地创建HTML解析器
  利用Xerces2.0为基础,应用程序通过JAXP实例化解析器对象时,可以透明地创建HTML解析器,此时只需要将NekoHTMLjar文件,在CLASSPATH中放在Xercesjar文件之前即可。nekohtmlXni.jar中的META-INF/services/org.apache.xerces.xni.parser.XMLParserConfiguration文件会被Xerces的读取并取代标准的设置文件,此处org.apache.xerces.xni.parser.XMLParserConfiguration文件的内容就是一个字符串"org.cyberneko.html.HTMLConfiguration"。这种方法的好处是简单透明,缺点是影响了Xerces在其它情况下的使用。

2、便利的HTML解析器类
  要想避免上述的问题,可以使用org.cyberneko.html.parsers包的DOMSAX解析器类来创建解析器,这两个类都使用了HTMLConfiguration类。解析器一旦创建之后,就可以解析HTML文件,并用标准的XML接口来访问文件中的信息,就象面对的是一个XML文件一样。
  下面的代码是NekoHTML自带的例程,我改了一下,使其可以显示HTML文件内容,而不显示类的名字。

package sample;

 

 

import org.cyberneko.html.parsers.DOMParser;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.w3c.dom.Document;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.w3c.dom.Node;

 

 

public class TestHTMLDOM {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    public static void main(String[] argv) throws Exception {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        DOMParser parser = new DOMParser();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        for (int i = 0; i < argv.length; i++) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            parser.parse(argv[i]);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            print(parser.getDocument(), "");
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    public static void print(Node node, String indent) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

//        System.out.println(indent+node.getClass().getName());
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        if (node.getNodeValue() != null){
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            if("".equals(node.getNodeValue().trim())){
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            }else{
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            System.out.print(indent);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            System.out.println(node.getNodeValue());
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

               }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

       
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        Node child = node.getFirstChild();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        while (child != null) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            print(child, indent+" ");
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            child = child.getNextSibling();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

}
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

编译运行如下:

cd $NEKOHTML_HOME
cp build_html.xml build.xml
ant
java -cp nekohtml.jar;nekohtmlSamples.jar;xmlParserAPIs.jar;xercesImpl.jar sample.TestHTMLDOM test.html


如果一切正常可以显示HTML的内容了。
3
、文档片段解析
  除了DOMSAX类,NekoHTML还提供了一个实验性质的DOMFragmentParser类,用以解析HTML文件的片段。我个人认为,由于浏览器的强大的容错能力,即使一个片段的HTML文件,也可以正确显示,由此也变相地造成了很多人不再关心的HTML的完整要求了。这个类,也许将是用的最多的。下面,看看nutch是如何使用nekoHTML的。

package net.nutch.fetcher;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

...
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.cyberneko.html.parsers.*;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.xml.sax.*;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.w3c.dom.*;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.w3c.dom.html.*;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.apache.html.dom.*;

 

 

/* A simple fetcher. */
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

public class Fetcher {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        ....
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    private DOMFragmentParser parser = new DOMFragmentParser();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        ....
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    private void handleFetch(URL url, FetchListEntry fle, Http.Response response)
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      throws IOException, SAXException {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

     
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //判断HTTP应答包的类型,只放过html文件
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      String contentType = response.getHeader("Content-Type");
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      if (contentType != null && !contentType.startsWith("text/html"))
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        throw new IOException("Unknown content-type: " + contentType);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //创建文件片段对象
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      DocumentFragment node = new HTMLDocumentImpl().createDocumentFragment();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //解析HTML内容
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      parser.parse(new InputSource(new ByteArrayInputStream(response.getContent())),node);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //取得全部文本内容
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      StringBuffer sb = new StringBuffer();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      getText(sb, node);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      String text = sb.toString();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //取得标题信息
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      sb.setLength(0);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      getTitle(sb, node);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      String title = sb.toString().trim();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //取得该页所有的出链
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      ArrayList l = new ArrayList();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      getOutlinks(url, l, node);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

     
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      //显示结果,存储信息
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      Outlink[] outlinks = (Outlink[])l.toArray(new Outlink[l.size()]);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      LOG.fine("found " + outlinks.length + " outlinks in " + url);

 

 

      outputPage(new FetcherOutput(fle, MD5Hash.digest(response.getContent()),
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

                                   true, title, outlinks),
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

                 new FetcherContent(response.getContent()),
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

                 new FetcherText(text));
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  private static void getText(StringBuffer sb, Node node) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    if (node.getNodeType() == Node.TEXT_NODE) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      sb.append(node.getNodeValue());//取得结点值,即开始与结束标签之间的信息
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    NodeList children = node.getChildNodes();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    if ( children != null ) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      int len = children.getLength();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      for ( int i = 0; i < len; i++ ) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        getText(sb, children.item(i));//递归遍历DOM
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  }

 

 

  private static boolean getTitle(StringBuffer sb, Node node) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    if (node.getNodeType() == Node.ELEMENT_NODE) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      if ("title".equalsIgnoreCase(node.getNodeName())) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        getText(sb, node);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        return true;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    NodeList children = node.getChildNodes();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    if (children != null) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      int len = children.getLength();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      for (int i = 0; i < len; i++) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        if (getTitle(sb, children.item(i))) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

          return true;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    return false;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  }

 

 

  private static void getOutlinks(URL base, ArrayList outlinks, Node node) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    if (node.getNodeType() == Node.ELEMENT_NODE) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      if ("a".equalsIgnoreCase(node.getNodeName())) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        StringBuffer linkText = new StringBuffer();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        getText(linkText, node);

 

 

        NamedNodeMap attrs = node.getAttributes();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        String target= null;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        for (int i= 0; i < attrs.getLength(); i++ ) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

          if ("href".equalsIgnoreCase(attrs.item(i).getNodeName())) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            target= attrs.item(i).getNodeValue();//DOM树中,属性是一个结点。
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            break;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

          }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        if (target != null)
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

          try {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            URL url = new URL(base, target);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            outlinks.add(new Outlink(url.toString(),linkText.toString().trim()));
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

          } catch (MalformedURLException e) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

            // don't care
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

          }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    NodeList children = node.getChildNodes();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    if ( children != null ) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      int len = children.getLength();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      for ( int i = 0; i < len; i++ ) {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        getOutlinks(base, outlinks, children.item(i));//递归遍历DOM
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

      }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  }    
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  ....
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

}


注意,此处传递给解析过程parse的文档片段对象,必须是由org.w3c.dom.html.HTMLDocument类型的DOM文档对象创建,否则有异常。
  HTMLConfiguration可以用于创建任何基于XNI解析器,可参考下例

package sample;

 

 

import org.apache.xerces.parsers.AbstractSAXParser;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

import org.cyberneko.html.HTMLConfiguration;

 

 

public class HTMLSAXParser extends AbstractSAXParser {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    public HTMLSAXParser() {
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

        super(new HTMLConfiguration());
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

    }
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

}
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

三、设置解析器参数

  为了更加精确的控制解析的动作,nekohtml提供了相应的设置函数。如下列:

// settings on HTMLConfiguration
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

org.apache.xerces.xni.parser.XMLParserConfiguration config =
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  new org.cyberneko.html.HTMLConfiguration();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

config.setFeature("http://cyberneko.org/html/features/augmentations", true);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

config.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");

 

 

// settings on DOMParser
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

org.cyberneko.html.parsers.DOMParser parser =
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

  new org.cyberneko.html.parsers.DOMParser();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

parser.setFeature("http://cyberneko.org/html/features/augmentations", true);
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

 

nekohtml功能(feature)列表

功能

默认值

描述

http://cyberneko.org/html/features/balance-tags

True

是否允许增补缺失的标签。如果要以XML方式操作HTML文件,此值必须为真。此处提供设置功能,为了性能的原因。

http://cyberneko.org/html/features/balance-tags/ignore-outside-content

False

是否忽略文档根元素以后的数据。如果为false<html><bod>被忽略,所有的内容都被解析。

http://cyberneko.org/html/features/document-fragment

False

解析HTML片段时是否作标签增补。此功能不要用在DOMParser上,而要用在DOMFragmentParser上。

http://apache.org/xml/features/scanner/notify-char-refs

False

当遇到字符实体引用(如&#x20;)是否将(#x20)报告给相应地文档处理器。

http://apache.org/xml/features/scanner/notify-builtin-refs

False

当遇到XML内建的字符实体引用(如&amp;)是否将(amp)报告给相应地文档处理器。

http://cyberneko.org/html/features/scanner/notify-builtin-refs

False

当遇到HTML内建的字符实体引用(如&copy;)是否将(copy)报告给相应地文档处理器。

http://cyberneko.org/html/features/scanner/script/strip-comment-delims

False

是否剥掉<script>元素中的<!-- -->等注释符。

http://cyberneko.org/html/features/augmentations

False

是否将与HTML事件有关的infoset项包括在解析管道中。

http://cyberneko.org/html/features/report-errors

False

是否报告错误。


nekohtml
属性列表

属性

默认值

值域

描述

http://cyberneko.org/html/properties/filters

null

XMLDocumentFilter[]

在解析管道的最后按数组顺序追加自定义的处理组件(过滤器),必须为数组类型。

http://cyberneko.org/html/properties/default-encoding

Windows-1252

IANA encoding names

默认的HTML文件编码

http://cyberneko.org/html/properties/names/elems

upper

upper,lower,match

如果整理识别出的元素名称

http://cyberneko.org/html/properties/names/attrs

lower

upper,lower,no-change

如果整理识别出的属性名称

 

 

四、管道过滤器


  Xerces Native Interface (XNI)定义了一个解析器配置框架,在那儿一个个解析器以模块化组件的形式组成一个管道。这样一来,通过重新安排已有组件和/或新定制开发的组件,就可完成一个新的解析器配置工作。由于nekohtml是采用这个配置框架开发的,所以对解析器新增功能就很简单通过在默认的nekohtml解析管道的末端增加文档过滤器来实现。
  要新开发一个过滤器,很简单地实现xerces2org.apache.xerces.xni.parser包中的XMLDocumentFilter接口即可。这个接口,一方面使组件成为管道中上一级的事件处理器,另一方面又成为下级的信息源。针对nekohtml的过滤器开发,只需简单地扩展org.cyberneko.html.filters包中的DefaultFilter类即可。
  将自行开发的过滤器加入管道,可参考以下两种办法:

XMLDocumentFilter noop = new DefaultFilter();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

XMLDocumentFilter[] filters = { noop };

 

 

XMLParserConfiguration parser = new HTMLConfiguration();
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

parser.setProperty("http://cyberneko.org/html/properties/filters", filters);


  nekohtmlorg.cyberneko.html.filters 包中有DefaultFilter
ElementRemover
IdentityWriter,能实现动态插入内容、删除元素、序列化HTML文档等,不详细述。

请参考:
DOMAPI
学习
http://hedong.3322.org/archives/000228.html

SAXAPI学习笔记(2
http://hedong.3322.org/archives/000232.html

1 条评论: