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

11 投票
2 回答
34030 浏览
提问于 2025-04-18 12:29

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

0

我在使用 DjangoPython 3.4 的时候遇到了这个错误。我当时想让它和 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)
16

你的问题是,这个数据不是UTF-8格式。你得到的是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')

当没有设置charset参数时,它默认使用UTF-8,这对于JSON数据来说是合适的默认值。

另外,你也可以使用requests来加载JSON响应,它会自动处理解码(包括针对JSON响应的UTF编码自动检测)。

还有一点需要注意的是:PEP 263源代码编码注释仅用于解释你的源代码,包括字符串字面量。它和外部数据的编码(比如文件、网络数据等)没有关系。

撰写回答