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