1、問題:
在用urllib2.urlopen()打開的網頁顯示亂碼,查看原網頁其用的charset='gb2312'
所以見獲取到的網頁用decode('gb2312')解碼,
但是發現偶爾能行,大部分時候不行,非常奇怪,不行的時候報錯:
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 11346-11347: illegal multibyte seq
2、找原因
使用python 的chardet模塊檢查了字串的編碼
pip install chardet
import chardet
import urllib2
#可根據需要,選擇不同的數據
TestData = urllib2.urlopen('http://www.baidu.com/').read()
print chardet.detect(TestData)
# 運行結果:
# {'confidence': 0.9250178129846179, 'language': 'Chinese', 'encoding': 'GB2312'}
這就是原因,92%的概率爲gb2312。看來有可能某位在該網頁裏注入了少量其他編碼字符, 而且有一個隨機性,所以有時候行有時候不行
3、解決:
在decode()中加入參數,如:
decode('gb2312', 'ignore'): 意思上忽略非gb2312編碼的字符,這樣就不會報錯了。
參數如下:
默認的參數就是strict,代表遇到非法字符時拋出異常;
如果設置爲ignore,則會忽略非法字符;
如果設置爲replace,則會用?號取代非法字符;
如果設置爲xmlcharrefreplace,則使用XML的字符引用。
4、完整代碼
#coding:utf-8
import urllib2
from bs4 import BeautifulSoup
import re
import chardet
url = "http://www.xxx.com" #URL不便發佈
response = urllib2.urlopen(url)
html = response.read()
print chardet.detect(html)
html = html.decode('gb2312','ignore')
bs = BeautifulSoup(html,'lxml')
imgs = bs.find_all('img')
for img in imgs:
imgurl = img['src']
name = imgurl.split('/')[-1]
with open(name,'wb') as f:
try:
response = urllib2.urlopen(imgurl)
f.write(response.read())
f.close()
except:
pass #如果圖片不存在或訪問中報錯,不做處理,直接跳到下一個URL即可
'''
從某網頁上下載圖片
'''
5、其它原因
還有一個可能的原因是:
一些規模較大的網站是以gzip的壓縮格式輸出頁面的,所以在用BS解析之前需要先判斷該網頁是否經過壓縮。如果經過壓縮則先進行解壓操作。解壓操作如下:
import gzip
import StringIO
import urllib2
ur1='http://www.runoob.com/python/python-exercise-example1.html'
reponse=urllib2.urlopen(ur1)
reponse_data=reponse.read()
data = StringIO.StringIO(reponse_data)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
print html