解决python3 UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f608' in position。。。

1、问题描述:

爬虫后的网页保存文件的时候,将uft-8的编码写入文档,并输出的时候,出现这了这个报错,说gbk无法编码\U0001f608

UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f608' in position 76036: illegal multibyte sequence

2、 测试代码:

import urllib.request

res = urllib.request.urlopen('http://www.baidu.com')
htmlBytes = res.read()
print(htmlBytes.decode('utf-8'))

with open("test.html",'w') as f:
    f.write(htmlBytes.decode('utf-8'))

运行后:
print打印正确,写入文件错误
在这里插入图片描述

3、错误分析:

通过查看网页源码
在这里插入图片描述
这说明网页的确用的是utf-8
而open函数默认的编码格式不是utf-8才导致保存失败,我们只需要设置open函数的编码格式为utf-8就可以了。
查看open函数文档
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
由此我这个时windows下默认编码格式是gbk的,所以需要设置一下。

4、解决办法:

4.1改变终端输出的编码格式为utf-8:

#import io
#import sys
#sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码

4.2改变写文件的编码格式为utf-8:

 with open(filename,'w',encoding="utf-8") as f:
        f.write(data)

4.3 修改后的代码运行正常:

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

废人一枚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值