[python3.x] 利用chardet检测网页编码
生活随笔
收集整理的這篇文章主要介紹了
[python3.x] 利用chardet检测网页编码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
環境: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 0blog = fp.read() # python3.x read the html as html code bytearrayfp.close()#writeFile("t.html", blog)# get encoding stringcodedetect = chardet.detect(blog)['encoding']print('%s <- %s' %(blogurl, codedetect))return 1if __name__=='__main__':if len(sys.argv) == 1:print('''usage:python DetectURLCoding.py http://xxx.com''')else:v = blog_detect(sys.argv[1])print(v)
運行結果:
?
總結
以上是生活随笔為你收集整理的[python3.x] 利用chardet检测网页编码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 条件注释判断浏览器版本!--[if lt
- 下一篇: cocos creator fgui 按