原创文章,转载请注明。
爬虫往往会遇到乱码问题。最简单的方法是依据http的响应信息来获取编码信息。但假设对方站点的响应信息不包括编码信息或编码信息错误,那么爬虫取下来的信息就非常可能是乱码。
好的解决的方法是直接依据页面内容来自己主动推断页面的编码。
如Mozilla公司的firefox使用的universalchardet编码自己主动检測工具。
juniversalchardet是universalchardet的java版本号。
源代码开源于 
https://github.com/thkoch2001/juniversalchardet
       自己主动编码主要是依据统计学的方法来推断。详细原理。能够看http://www-archive.mozilla.org/projects/intl/UniversalCharsetDetection.html
如今以Java爬虫经常使用的httpclient来解说怎样使用。看下面关键代码:
UniversalDetector encDetector = new UniversalDetector(null);
    while ((l = myStream.read(tmp)) != -1) {
        buffer.append(tmp, 0, l);
        if (!encDetector.isDone()) {
            encDetector.handleData(tmp, 0, l);
        }
    }
encDetector.dataEnd();
String encoding = encDetector.getDetectedCharset();
if (encoding != null) {
    return new String(buffer.toByteArray(), encoding);
}
encDetector.reset();myStream.read(tmp)) 读取httpclient得到的流。我们要做的就是在读流的同一时候,运用juniversalchardet来检測编码,假设有符合特征的编码的出现,则最后可通过detector.getDetectedCharset() 能够得到编码。否则返回null。至此,检測工作结束。通过String的构造方法来进行按一定编码构建字符串。
        
 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号