在保存网页信息时 出现的标题错误
response=requests.get('http://www.runoob.com/w3cnote/python-ten-minute-introductory-tutorial.html')
print(response.text)
with open('python01.html','w+') as f:
f.write(response.text)
出现了
UnicodeEncodeError: 'gbk' codec can't encode character '\xe5' in position 259: illegal multibyte sequence
解决办法 指定一下编码即可
with open('python01.html','w+',encoding='utf-8') as f:
若保存网页还是乱码 请参考下面的方法 :
response=requests.get('http://www.runoob.com/w3cnote/python-ten-minute-introductory-tutorial.html')
print(response.content.decode('utf-8'))
with open('python01.html','w+',encoding='utf-8') as f:
f.write(response.content.decode('utf-8'))
关于response.text 和response.content的区别
response.text
类型 : str
解码类型:根据HTTP头部对响应的编码做出有根据的推测,推测的文本编码
如何修改编码方式:response.encoding="gbk"
response.content
- 类型:bytes
- 解码类型: 没有指定
- 如何修改编码方式:response.content.deocde(“utf-8”)
简单来说
resp.text返回的是Unicode型的数据。
resp.content返回的是bytes型也就是二进制的数据。
本文详细介绍了在使用Python的requests库抓取网页时遇到的编码错误问题,特别是UnicodeEncodeError,并提供了有效的解决方案,包括正确设置文件编码和使用response.content进行解码。

8496

被折叠的 条评论
为什么被折叠?



