当我使用 python lxml 库(最新版本) 指定我自己的编码时,我收到 LookupError。
发生查找错误。参数:(“未知编码:'b'utf-8-sig''”,)
parser = etree.XMLParser(encoding="utf-8-sig")
xml = etree.parse(source=response_bytes_io, parser=parser)
由于某些原因,lxml 不知道“utf-8-sig”,而它是 python 3 的标准编码。参见 https://docs.python.org/3/library/codecs.html#standard-encodings
知道如何解决这个问题吗?
最佳答案
一个很好的解决方案,即使我不明白它为什么有效
长话短说,使用utf-8
而不是 utf-8-sig
即使存在 UTF-8 编码的 BOM,它也能正常工作:
>>> data = b'\xef\xbb\xbf<test/>'
>>> lxml.etree.parse(io.BytesIO(data), parser=lxml.etree.XMLParser(encoding='utf-8'))
<lxml.etree._ElementTree object at 0x7f3403e47730>
注意必须是utf-8
,而不是 utf8
尽管后者通常被 Python 接受为别名:
>>> lxml.etree.parse(io.BytesIO(b'\xef\xbb\xbf<test/>'), parser=lxml.etree.XMLParser(encoding='utf8', remove_blank_text=True))
Traceback (most recent call last):
...
lxml.etree.XMLSyntaxError: Start tag expected, '<' not found, line 1, column 1
背景信息
lxml 是 libxml2 库的包装器。出于这个原因,encoding
参数传递给 XMLParser
不是 Python 编码的名称,而是 iconv 编码名称。我不得不潜入the lxml source弄清楚这一点,并可以通过例如检查来确认它OSF00010004
,我的系统上的 iconv 支持它,但 Python 不支持它:
>>> lxml.etree.parse(io.BytesIO(b'<test/>'), parser=lxml.etree.XMLParser(encoding='OSF00010004'))
<lxml.etree._ElementTree object at 0x7f8baa6adc30>
>>> b'<test/>'.decode('OSF00010004')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
LookupError: unknown encoding: OSF00010004
我们可以使用 iconv -l
列出支持的编码,但没有等效于 Python 的 BOM 剥离 utf-8-sig
.显然路过utf-8
足够好。
值得一提的是,libxml2 只适用于 UTF-8 编码的字符串,我们可以从 lxml FAQ 中了解到这一点。 :
The text encoding that libxml2 uses internally is UTF-8, so parsing from a Unicode file means that Python first reads a chunk of data from the file, then decodes it into a new buffer, and then copies it into a new unicode string object, just to let libxml2 make yet another copy while encoding it down into UTF-8 in order to parse it.
这对性能有影响,如 FAQ 条目的详细信息。
我理解的简单解决方法
我们可以先解码再解析:
response_string = response_bytes_io.read().decode('utf-8-sig')
xml = etree.fromstring(response_string)
如上所述,这效率较低,因为 Python strings are not internally stored as UTF-8因此在 libxml2 可以使用它之前必须将其重新编码为 UTF-8。
您还需要注意,如果 XML 包含类似 <?xml version="1.0" encoding="UTF-8"?>
的编码声明,此方法将失败。 :
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
如果您要处理来自第三方来源的 XML,这可能会破坏交易。
我理解的更好的解决方法
我们也可以自己去掉 UTF-8 编码的 BOM,因为它总是三个字节 \xef\xbb\xbf
.
遗憾的是,在类似文件的对象上执行此操作比在字符串上执行此操作要复杂一些,因为您无法预读。将文件包装在 io.BufferedReader
中给你 peek()
函数,但您无法控制它返回多少字节。
所以安全的方法是首先将所有内容读入缓冲区:
response_bytes = response_bytes_io.read()
if response_bytes.startswith(b'\xef\xbb\xbf'):
response_bytes = response_bytes[3:]
parser = etree.XMLParser(encoding='utf-8')
xml = etree.parse(source=io.BytesIO(response_bytes), parser=parser)
这比直接在流上操作效率低,因为解析会延迟到整个响应已被读取,但它仍然比额外的解码和重新编码过程更有效。
关于python - 发生 lxml LookupError。参数 : ("unknown encoding: ' b'utf-8-sig ''", ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50970691/