【python学习】判断网站的编码

一、关键点

1.chardet的使用

http://www.pythonclub.org/modules/chardet chardet安装依赖于setuptools,因此需安装setuptools http://www.cnblogs.com/mindmac/archive/2012/03/07/2383441.html chardet不仅可以用来检测,也可以用来转换,几句就够:

 if codedetect <> 'utf-8': #是否是utf-8
try:
blog = unicode(blog, codedetect) #不是的话,则尝试转换
#print blog
blog = blog.encode('utf-8')
except:
print u"bad unicode encode try!"
return 0

  2.urllib2库的使用

基本的使用方法是:先urlopen,再read()就可以获得网页内容,更多的等待以后发掘 3.argv参数的使用,python中貌似没有argc,可以用len(argv)替代 http://paulhsu.blogspot.com/2010/10/pyhtonargcargv.html

二、具体实现

#-*- coding:utf-8 -*-
#FileName:code_detect.py
#Author:Xue Weiwei@USTC
#Last-Modify:2012-5-15
'''检测网页的编码
@note:利用chardet库'''
import chardet
import urllib2
import sys
def codedetect(url):
'''
检测某一网页的编码方式
@param: url 待检测网址
'''
try:
fp=urllib2.urlopen(url)
except Exception, e:
print e
return 0
blog=fp.read()
code=chardet.detect(blog)["encoding"]
print code
if __name__=='__main__':
if len(sys.argv)!=2:
print '''usage:\npython code_detect.py http://xxxx.com'''
#codedetect("http://www.163.com")
else:
codedetect(sys.argv[1])
原文地址:https://www.cnblogs.com/xweiwei/p/2732531.html