首页 > 其他 > 详细

chardet字符集检测模块

时间:2015-08-02 01:02:57      阅读:254      评论:0      收藏:0      [点我收藏+]

chardet字符集检测模块


chardet 字符集检测模块

需要安装

pip install chardet 

可以检测网页,也可以检测字符串

import urllib
import chardet

‘‘‘
从网页的头部信息可以查看的内容
网页的大小,编码等(有时候可能为空)

可以使用chardet来检测网页的编码
‘‘‘

url = ‘http://baidu.com‘

headerInfo = urllib.urlopen(url).info()

# headerInfo.getparam(‘charset‘)

context = urllib.urlopen(url)

print chardet.detect(context)

返回的是一个字典,可以通过字典的key拿到对应的值

result = chardet.detect(context)

print result[‘encoding‘]

代码整理

import urllib
import chardet

‘‘‘
代码的封装
‘‘‘

def auto_getCharset(targetUrl):
    context = urllib.urlopen(targetUrl).read()
    result = chardet.detect(context)
    return result[‘encoding‘]

if __name__==‘__main__‘:
    urls = [‘http://www.csdn.net/‘,‘http://www.imooc.com/‘,‘http://www.51cto.com/‘,
            ‘http://www.mukedaba.com/‘,‘http://www.nowcoder.com/‘]
    for url in urls:
        print url , auto_getCharset(url)

版权声明:本文为博主原创文章,未经博主允许不得转载。

chardet字符集检测模块

原文:http://blog.csdn.net/weiyongxuan/article/details/47193245

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!