【发布时间】:2019-09-17 23:02:44
【问题描述】:
我正在尝试在 python 程序中进行网络抓取。我得到的 html 页面是 utf-8 格式。我在使用以下字符时遇到问题:'????' 我相信这是由于字符占用 4 个字节(编码为 b'\xf0\xa0\x86\xa2')。我还注意到Windows对utf-8不友好,我是Windows用户。
我试图找到一种方法来解析文本并删除错误的 4 字节字符,因为它出现了几个小时但没有成功。由于该字符是整行文本的一部分,因此我想解析该行并仅删除不可解码的字符。
def TryDecode(toParse):
try:
result = toParse.decode('utf-8', 'ignore') #No exception
except UnicodeEncodeError:
result = 'error'
return result
badutf = b' <li ...>\xf0\xa0\x86\xa2</li>\r\n'
res = TryDecode(badutf)
print("I see this")
print(res) # UnicodeEncodeError
print("I do not see this.")
预期结果:在 try 块中抛出错误或根本不抛出错误。 实际结果:直到第二个打印语句都没有错误。 注意:如果我包括 '????'我的脚本中的字符,也无法从 IDE 运行它。
编辑:感谢有用的建议,我现在明白了这个问题。如果其他人遇到类似问题,这是一个解决方案:
UCSTWOMAX = 65536 # Max value for UCS-2 formatting
def TryDecode(toParse):
try:
parsed = toParse.decode('utf-8', 'ignore')
result = ''
for c in parsed:
if ord(c) < UCSTWOMAX:
result += c
except UnicodeEncodeError:
result = 'error'
return result
badutf = b' <li ...>\xf0\xa0\x86\xa2</li>\r\n'
res = TryDecode(badutf)
print(res)
print("I see this now.")
【问题讨论】:
-
您可能会发现例如/questions/6344853/python-unicode-in-windows-terminal-encoding-used 有用。