利用chardet检测网页编码

本文介绍如何在Windows环境下利用Python的Chardet库来检测网页的编码方式。通过下载并安装Chardet库,编写了一个简单的Python脚本,该脚本能自动获取指定网址的内容并检测其编码类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境:Win7_x64 + python3.4.3

需要先下载chardet并进行安装,下载地址:https://pypi.python.org/packages/source/c/chardet/chardet-2.3.0.tar.gz

安装:进入解压后的目录,在命令窗口执行: Python setup.py install

写个测试的python脚本吧(DetectURLCoding.py):

#coding:utf-8  
'''''python 3.x'''  
  
import sys  
import urllib.request  
import chardet  
  
# 将data写入文件fname  
def writeFile(fname, data):  
    f = open(fname, "wb")  
    if f:  
        f.write(data)  
        f.close()  
  
def blog_detect(blogurl):  
    '''''检测编码方式'''  
    try:  
        fp = urllib.request.urlopen(blogurl)  
    except Exception as e:  
        print(e)  
        print('download exception-[%s]' %blogurl)  
        return 0  
    blog = fp.read()    # python3.x read the html as html code bytearray  
    fp.close()  
    #writeFile("t.html", blog)  
      
    # get encoding string  
    codedetect = chardet.detect(blog)['encoding']  
    print('%s <- %s' %(blogurl, codedetect))  
    return 1  
  
if __name__=='__main__':  
    if len(sys.argv) == 1:  
        print('''''usage: 
            python DetectURLCoding.py http://xxx.com''')  
    else:  
        v = blog_detect(sys.argv[1])  
        print(v)  # 何问起 hovertree.com

运行结果:

D:\profile\Desktop>PYTHON de.py http://hovertree.com/  
http://hovertree.com/ <- utf-8  
1  
  
D:\profile\Desktop>PYTHON de.py http://photo.cankaoxiaoxi.com/roll10/2015/0318/709734.shtml  
http://photo.cankaoxiaoxi.com/roll10/2015/0318/709734.shtml <- utf-8  
1  

web前端:http://www.cnblogs.com/roucheng/p/texiao.html

转载于:https://www.cnblogs.com/roucheng/p/chardet.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值