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

运行以后,结果报错:

 从提示可以看到,第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

 果然这样就没有再报错

 

  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值