三林小猎人 发表于 2016-4-8 18:07:53

爬取新浪微博图片关于UnicodeDecodeError报错

本帖最后由 三林小猎人 于 2016-4-8 18:09 编辑

import urllib.request
import re


def open_url(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 UBrowser/5.6.11466.7 Safari/537.36')

page = urllib.request.urlopen(req)
html = page.read().decode('utf-8')

return html

def get_img(html):
p = r'<img node-type="imgShow" src="(^http+\.jpg)"'
imglist = re.findall(p,html)


for each in imglist:
    filename = each.split('/')[-1]
    urllib.request.urlretrieve(each,filename,None)



if __name__ == '__main__':
url = 'http://weibo.com/u/3640184915/home?wvr=5'
get_img(open_url(url))





Traceback (most recent call last):
File "C:\Users\dell\Desktop\weibotupian.py", line 27, in <module>
    get_img(open_url(url))
File "C:\Users\dell\Desktop\weibotupian.py", line 10, in open_url
    html = page.read().decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 319: invalid continuation byte

但是网页上的charset属性确实是utf-8啊!!!!

hldh214 发表于 2016-4-8 18:15:56

因为html被压缩了, 用gzip模块试试

三林小猎人 发表于 2016-4-8 20:26:32

hldh214 发表于 2016-4-8 18:15
因为html被压缩了, 用gzip模块试试

恩,好的,我试一试,谢谢!!

三林小猎人 发表于 2016-4-8 20:41:02

hldh214 发表于 2016-4-8 18:15
因为html被压缩了, 用gzip模块试试

您好!我也是刚开始学,不知道gzip这个模块怎么用,请您赐教!谢谢了!

mongoole 发表于 2021-12-7 15:38:16

需要"unicode_escape"解码
页: [1]
查看完整版本: 爬取新浪微博图片关于UnicodeDecodeError报错