解决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 修改后的代码运行正常:

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章