---
title: "htmlparser解析html时的编码问题"
author: "zhaoImpulse"
date: "2011-11-23T18:36:46Z"
tags: []
categories: ["编程语言"]
slug: "htmlparser-html"
draft: false
lastmod: "2011-11-23T18:36:46Z"
id: 1275280
url: "https://zhaoimpulse.iteye.com/blog/1275280"
---

htmlparser是个解析html文件的一个很不错的库。它能够过滤几乎所有的html元素，而只提供给我们纯文本。但是要用它来解析html，需要好好的搞一个搞编码问题。

htmlparser的默认编码类型是iso,所以我们要根据文件内容的不同来手动设置一个所需要的编码。

 

```
Parser myParser = new Parser(file.getAbsolutePath());
myParser.setEncoding("unicode");
```

通常html里都会有这样一句话&lt;meta http-equiv='Content-Type' content='text/html;charset= gbk' /&gt;

用来表示该html的编码类型是什么，但当我们用普通方法来解析这个文件时

```
 public void get(String path){
        File f = new File(path);
        try {
            InputStreamReader isr = new FileReader(f);
            System.out.println(isr.getEncoding());
            char[] c = new char[128];
            while(isr.read(c)>0){
                String str = String.valueOf(c);
               // System.out.println(new String(str.getBytes(),"utf-8"));
            }
            InputStream is = new FileInputStream(f);
            byte[] b = new byte[1024];
            while(is.read(b)>0){
                //String.
                String str = new String(b,"unicode");
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}
```

 这句话没有意义，无论这句话所申明的编码类型是什么，我们要想解析这个文件，仍然只能用这个文件的编码类型来解析。

但当我们用到htmlparser时，这句话就有意义了。

```
Parser myParser;
        try {
            myParser = new Parser(path);
            System.out.println(myParser.getEncoding());
            myParser.setEncoding("unicode");
            HtmlPage htmlpage = new HtmlPage(myParser);
            System.out.println(myParser.getEncoding());
            myParser.visitAllNodesWith(htmlpage);
            // 通过htmlparser 获取body内容
            String body = htmlpage.getBody().toHtml();
            System.out.println(body);

        } catch (ParserException e) {
            e.printStackTrace();
        }
```

  这个代码运行时会报一个错org.htmlparser.util.EncodingChangeException: character mismatch (new: ? \[0xfe] != old:  \[0x20 ]) for encoding change from unicode to gbk at character offset 0

也就是说，htmlparser在解析html时，既要用到文件的编码，也要用到&lt;meta http-equiv='Content-Type' content='text/html;charset= gbk' /&gt;这句中的编码类型，而且它们必须一致。

当然，如果把&lt;meta http-equiv='Content-Type' content='text/html;charset= gbk' /&gt;这句删掉，那就没有任何问题了，但为了规范化

我们仍要加上这句，并强制这句中所写的编码类型和该html文件的编码类型一致。