UnicodeDecodeError: 'utf-8'编解码器无法解码字节错误。

11
我正在尝试从 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
2个回答

16
你的问题在于它不是UTF-8编码。你有UTF-16编码的数据,需要按照UTF-16进行解码:
>>> data = 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.decode('utf16')
'{ \r\n"id" : "1404830064696",\r\n"title" : "פיקוד העורף התרעה במרחב ",\r\n"data" : []\r\n}\r\n\r\n'
>>> import json
>>> json.loads(data.decode('utf16'))
{'title': 'פיקוד העורף התרעה במרחב ', 'id': '1404830064696', 'data': []}

如果您使用urllib.request从网站加载此内容,则Content-Type头应该包含一个charset参数,告诉您这一点;如果response是返回的urllib.request响应对象,则使用:
codec = response.info().get_content_charset('utf-8')

这里的默认编码是UTF-8,当没有设置charset参数时,默认为JSON数据的适当默认值。
或者,使用requests加载JSON响应,它会自动处理解码(包括针对JSON响应特定的UTF编码自动检测)。
另外需要注意的是,PEP 263源代码编解码注释仅用于解释您的源代码,包括字符串文字。它与外部来源(文件、网络数据等)的编码无关。

0

我在使用 Python 3.4Django 时遇到了这个错误。我试图使用 django-rest-framework 来解决它。

这是我的代码,可以解决UnicodeDecodeError: 'utf-8' codec can't decode byte error错误。

这是通过的测试:

import os
from os.path import join, dirname
import uuid
from rest_framework.test import APITestCase

class AttachmentTests(APITestCase):

    def setUp(self):
        self.base_dir = dirname(dirname(dirname(__file__)))

        self.image = join(self.base_dir, "source/test_in/aaron.jpeg")
        self.image_filename = os.path.split(self.image)[1]

    def test_create_image(self):
        id = str(uuid.uuid4())
        with open(self.image, 'rb') as data:
            # data = data.read()
            post_data = {
                'id': id,
                'filename': self.image_filename,
                'file': data
            }

            response = self.client.post("/api/admin/attachments/", post_data)

            self.assertEqual(response.status_code, 201)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接