• 用juniversalchardet解决爬虫乱码问题


    原创文章,转载请注明。


            爬虫往往会遇到乱码问题。最简单的方法是依据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的构造方法来进行按一定编码构建字符串。




           

  • 相关阅读:
    联表查询更新
    SQLServer 中多行数据合并成一行数据(一个字段)
    换行和回车的区别
    SQL语句中使用回车换行符
    g2o使用总结
    求导总结
    ubuntu14.04 升级gcc
    如何入门SLAM
    imu和canmera标定
    使用velodyne16线激光雷达跑loam-velodyne------包括激光雷达和imu的标定
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7206548.html
Copyright © 2020-2023  润新知