UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 的解决方法

最近初学网络爬虫,今天在练习使用Python的request模块的时候遇到了一个错误。

import requests

#发送请求
response = requests.get("https://jingyan.baidu.com/event/img/jdqsspzj252.jpg")
#保存
with open("a.jpg","wb") as f:
    f.write(response.content)

#获取网页数据的方法
#response.content.decode() : bytes转str
#response.content.decode("gbk")
#response.text :str text是属性不是方法

response = requests.get("https://www.sina.com.cn/")
with open("b.text","w") as r:
    r.write(response.content.decode("utf-8"))
#str转bytes叫encode,bytes转str叫decode

运行以后,结果报错:

UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 的解决方法_第1张图片

 从提示可以看到,第15行r.write(response.content.decode("utf-8"))出现了错误,但是它给我提示gbk编码不能解码成二进制字符,然而我设置成了utf-8,这完全对应不上。我能肯定第15行没有错误,于是就想我解码成了utf-8的格式是不是打开文件的时候出现了错误,于是就在第14行添加了打开格式,代码如下:

import requests

#发送请求
response = requests.get("https://jingyan.baidu.com/event/img/jdqsspzj252.jpg")
#保存
with open("a.jpg","wb") as f:
    f.write(response.content)
#获取网页数据的方法
#response.content.decode() : bytes
#response.content.decode("gbk")
#response.text :str text是属性不是方法

response = requests.get("https://www.sina.com.cn/")
with open("b.text","w",encoding="utf-8") as r:
    r.write(response.content.decode("utf-8"))
#str转bytes叫encode,bytes转str叫decode

 果然这样就没有再报错

UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 的解决方法_第2张图片

 

你可能感兴趣的:(Python语言)