一个朋友在抓取京东商城的页面时,因为京东的页面是gbk编码,所以需要使用decode进行转码。但是在使用decode转换编码时提示如下错误:’gbk’ codec can’t decode bytes in position 1-2: illegal multibyte sequence。
场景代码模拟如下:
#!/usr/bin/env python #coding=utf8 import urllib2 url = 'http://www.360buy.com/' req = urllib2.Request(url); f = urllib2.urlopen(req, timeout=30) html = f.read().decode('gbk') print html
看了代码感觉没有问题,于是笔者拿到自己的电脑上进行测试,可以正常运行。非常奇怪,为什么朋友电脑上的不能正常运行呢?在朋友电脑上进行了抓包尝试:
$ sudo tcpdump -i eth0 -nnA 'src host www.360buy.com' > test.txt
查看抓包结果都一堆乱乱的数据:
突然想起来来,这个应该是gzip压缩过后的数据。于是立马用gzip解压缩,然后就正常了。代码如下:
#!/usr/bin/env python #coding=utf8 import urllib2 import gzip, cStringIO url = 'http://www.360buy.com/' req = urllib2.Request(url); req.add_header('Accept-Encoding', 'gzip, deflate'); f = urllib2.urlopen(req, timeout=30) html = f.read() #gzip解压缩 if html[:6] == '\x1f\x8b\x08\x00\x00\x00': html = gzip.GzipFile(fileobj = cStringIO.StringIO(html)).read() html = html.decode('gbk') print html
小结
虽然上面的问题解决了,但是还有一点疑惑,为什么在自己的电脑上抓取到的网页是正常的,而在朋友的电脑上抓到的是gzip压缩的数据呢?
笔者和朋友的电脑都是ubuntu 12.04,python版本都是2.7.3。
转载请注明:快乐编程 » python抓取gbk网页时使用decode转码报错的问题