zoukankan      html  css  js  c++  java
  • Python chardet字符编码的判断

      使用 chardet 可以很方便的实现字符串/文件的编码检测。尤其是中文网页,有的页面使用GBK/GB2312,有的使用UTF8,如果你需要去爬一些页面,知道网页编码很重要的,虽然HTML页面有charset标签,但是有些时候是不对的。那么chardet就能帮我们大忙了。

    chardet的安装

       pip install chardet

    chardet实例

    >>> import urllib
    >>> rawdata = urllib.urlopen('http://www.google.cn/').read()
    >>> import chardet
    >>> chardet.detect(rawdata)
    {'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
    >>>

    chardet可以直接用detect函数来检测所给字符的编码。函数返回值为字典,有2个元数,一个是检测的可信度,另外一个就是检测到的编码

    chardet实例2

    import requests
    import chardet
      
    response = requests.get(“http://www.baidu.com”)
    encode = chardet.detect(response.content)   #response.content返回的是bytes型的数据, 如获取图片、文件
    print(encode)
    {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''} 
    response.encoding = encode["encoding"]     
    print(response.text)       #response.text返回的是Unicode型的数据。 如获取文本   
  • 相关阅读:
    框架代码 2
    框架代码 2
    个人资料  代码
    个人资料  代码
    XHTML表单
    框架代码 1
    计算机科学与技术学习反思录(转载)
    写在Blog点击数超过50000之后...
    小笨霖英语笔记本(6)水电
    SUN服务器及Solaris Serial Console常见设置问题
  • 原文地址:https://www.cnblogs.com/longsongpong/p/10077948.html
Copyright © 2011-2022 走看看