我正在尝试从urllib
获取响应并解码它
以可读的格式。文本是希伯来语,还包含{
和/
等字符
首页编码为:
# -*- coding: utf-8 -*-
原始字符串是:
b'\xff\xfe{\x00 \x00\r\x00\n\x00"\x00i\x00d\x00"\x00 \x00:\x00 \x00"\x001\x004\x000\x004\x008\x003\x000\x000\x006\x004\x006\x009\x006\x00"\x00,\x00\r\x00\n\x00"\x00t\x00i\x00t\x00l\x00e\x00"\x00 \x00:\x00 \x00"\x00\xe4\x05\xd9\x05\xe7\x05\xd5\x05\xd3\x05 \x00\xd4\x05\xe2\x05\xd5\x05\xe8\x05\xe3\x05 \x00\xd4\x05\xea\x05\xe8\x05\xe2\x05\xd4\x05 \x00\xd1\x05\xde\x05\xe8\x05\xd7\x05\xd1\x05 \x00"\x00,\x00\r\x00\n\x00"\x00d\x00a\x00t\x00a\x00"\x00 \x00:\x00 \x00[\x00]\x00\r\x00\n\x00}\x00\r\x00\n\x00\r\x00\n\x00'
现在我试着用以下方法解码它:
data = data.decode()
我得到以下错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
你的问题是那不是UTF-8。您有UTF-16编码数据,请按如下方式解码:
如果从带有
urllib.request
的网站加载,则Content-Type
头应该包含一个charset
参数告诉您这一点;如果response
是返回的urllib.request
响应对象,则使用:当没有设置
charset
参数时,默认为UTF-8,这是JSON数据的适当默认值。或者,使用^{} library 加载JSON响应,它自动处理解码(包括特定于JSON响应的UTF codec自动检测)。
另一个注意事项是,PEP 263 source code codec comment仅用于解释源代码,包括字符串文本。它与外部源(文件、网络数据等)的编码无关。
我用
Python 3.4
在Django
中得到这个错误。我想让这个和django-rest-framework一起工作。这是我的代码,它修复了unicodedecoderror:“utf-8”编解码器无法解码字节错误。
这是通过测试:
相关问题 更多 >
编程相关推荐