歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python處理中文編碼和判斷編碼

Python處理中文編碼和判斷編碼

日期:2017/3/1 9:35:44   编辑:Linux編程

在開發自用爬蟲過程中,有的網頁是utf-8,有的是gb2312,有的是gbk,如果不加處理,采集到的都是亂碼,解決的方法是將html處理成統一的utf-8編碼

針對python2.7。

代碼如下:

#coding:utf-8
#chardet 需要下載安裝
import chardet
#抓取網頁html
line = "http://www.linuxidc.com"
html_1 = urllib2.urlopen(line,timeout=120).read()
#print html_1
encoding_dict = chardet.detect(html_1)
#print encoding
web_encoding = encoding_dict['encoding']
if web_encoding == 'utf-8' or web_encoding == 'UTF-8':

html = html_1
else :
html = html_1.decode('gbk','ignore').encode('utf-8')
#有以上處理,整個html就不會是亂碼。

Python解析xml文檔實例 http://www.linuxidc.com/Linux/2012-02/54760.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved