UnicodeEncodeError:'gbk'编解码器无法编码字符:非法多字节序列

问题描述 投票:2回答:3

我想从网址获取html内容并使用正则表达式解析html内容。但是html内容有一些多字节字符。所以我遇到了标题中描述的错误。

有人能告诉我如何解决这个问题吗?

python unicode encode
3个回答
11
投票

您需要编辑您的问题以显示(1)您使用的代码(2)完整错误和追溯(3)所涉及的URL(4)您尝试编码为gbk的unicode字符是什么

你似乎以某种方式从html内容中的原始字节中获取了unicode字符 - 如何?在html内容中指定了什么编码?

然后(我猜)你试图将unicode字符写入文件,编码为u​​nicode为gbk。在此过程中,您收到如下错误:

>>> u'\uffff'.encode('gbk')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'gbk' codec can't encode character u'\uffff' in position 0: illegal multibyte sequence
>>>

如果html内容中的原始字节没有用gbk编码,那么很可能你有一些无法用gbk表示的unicode字符。在这种情况下,您可能希望使用原始编码对结果进行编码,或者在gb18030中对其进行编码,这可以采用任何unicode字符。

另一种可能性是你以某种方式破坏了原始字节或unicode。我当然希望你的正则表达式是在unicode上进行的,而不是像gb2312,gbk等那样的可变长度字符编码。

更新:

这是您的代码段:

import sys, urllib.request
url = "http://www.meilishuo.com"
wp = urllib.request.urlopen(url)
content = wp.read()
str_content = content.decode('utf-8')
fp = open("web.txt","w")
fp.write(str_content)
fp.close() 

从那以后我不得不推论: (1)您正在运行Python 3.x. (2)sys.defaultencoding ==“gbk” - 否则你不会收到前面报告过的部分错误信息。

由于我的sys.defaultencoding不是'gbk',我用gbk_content = str_content.encode('gbk')替换了你的最后3行,并用Python 3.1.2运行了修改后的代码段。

观察:

(1)网站有charset = utf-8,用utf-8解码OK (2)错误信息:UnicodeEncodeError: 'gbk' codec can't encode character '\u2764' in position 35070: illegal multibyte sequence

\u2664是一个dingbat(HEAVY BLACK HEART)。该网站充满活力;在另一次尝试中,第一个犯罪角色是\ xa9(版权标志)。

因此,网页包含未在gbk中映射的Unicode字符。选项是

(1)使用'gbk'进行编码,但使用'replace'选项 (2)使用'gbk'进行编码,但使用'ignore'选项 (3)使用支持所有Unicode字符(utf-8,gb18030)的编码进行编码,并且您有一个显示机制,可以呈现所有不在gbk中的字符


3
投票

尝试

open(file, 'r', encoding='utf-8')

代替

open(file, 'r')

1
投票

结合上面的答案,我发现以下代码非常有效。

import requests
r = requests.get("https://www.example.com/").content
str_content = r.decode('utf-8')
fp = open("contents.txt","w", encoding='utf-8')
fp.write(str_content)
fp.close()
© www.soinside.com 2019 - 2024. All rights reserved.