原创文章,转载请注明。
爬虫往往会遇到乱码问题。最简单的方法是根据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的构造方法来进行按一定编码构建字符串。