我试图通过遵循udacity课程在python中创建一个爬虫。我有这个方法get_page()
返回页面的内容。
def get_page(url):
'''
Open the given url and return the content of the page.
'''
data = urlopen(url)
html = data.read()
return html.decode('utf8')
原来的方法只是返回data.read()
,但这样我就不能像str.find()
那样进行操作。快速搜索后,我发现我需要解码数据。但现在我收到了这个错误
UnicodeDecodeError:'utf-8'编解码器无法解码位置1中的字节0x8b:无效的起始字节
我在SO中发现了类似的问题,但没有一个专门用于此。请帮忙。
您正在尝试解码无效的字符串。
任何有效UTF-8字符串的起始字节必须在0x00
到0x7F
的范围内。所以0x8B
绝对是无效的。来自RFC3629 Section 3:
在UTF-8中,使用1到4个八位字节的序列对来自U + 0000..U + 10FFFF范围(UTF-16可访问范围)的字符进行编码。一个“序列”的唯一八位字节将高阶位设置为0,其余7个字节用于编码字符编号。
您应该发布您尝试解码的字符串。
也许该页面使用其他字符编码进行编码,但是'utf-8'。因此起始字节无效。你可以做到这一点。
def get_page(self, url):
if url is None:
return None
response=urllib.request.urlopen(url)
if response.getcode()!=200:
print("Http code:",response.getcode())
return None
else:
try:
return response.read().decode('utf-8')
except:
return response.read()