这是处理 UTF-8 时的一个常见错误 - “无效标记”
在我的示例中,它来自于处理不尊重 unicode 字符的 SOAP 服务提供者,只是将值截断为 100 个字节并忽略第 100 个字节可能位于多字节字符的中间:例如:
<name xsi:type="xsd:string">浙江家庭教会五十人遭驱散及抓打 圣诞节聚会被断电及抢走物品(图、视频\xef\xbc</name>
最后两个字节是 3 字节 unicode 字符的剩余部分,在截断刀假定世界使用 1 字节字符之后。下一站,sax 解析器和:
xml.sax._exceptions.SAXParseException: <unknown>:1:2392: not well-formed (invalid token)
我不再关心这个角色了。它应该从文档中删除并允许 sax 解析器运行。
除了这些值之外,XML 回复在所有其他方面都是有效的。
问题:如何在不解析整个文档并重新发明 UTF-8 编码来检查每个字节的情况下删除这个字符?
使用:Python+SUDS
最佳答案
事实证明,SUDS 将 xml 视为类型“字符串”(不是 unicode),因此这些是编码值。
1) 过滤器:
badXML = "your bad utf-8 xml here" #(type <str>)
#Turn it into a python unicode string - ignore errors, kick out bad unicode
decoded = badXML.decode('utf-8', errors='ignore') #(type <unicode>)
#turn it back into a string, using utf-8 encoding.
goodXML = decoded.encode('utf-8') #(type <str>)
2) SUDS:见https://fedorahosted.org/suds/wiki/Documentation#MessagePlugin
from suds.plugin import MessagePlugin
class UnicodeFilter(MessagePlugin):
def received(self, context):
decoded = context.reply.decode('utf-8', errors='ignore')
reencoded = decoded.encode('utf-8')
context.reply = reencoded
和
from suds.client import Client
client = Client(WSDL_url, plugins=[UnicodeFilter()])
希望这对某人有帮助。
注意:感谢John Machin !
参见:Why is python decode replacing more than the invalid bytes from an encoded string?
python issue8271关于 errors='ignore'
可以在这里妨碍你。如果没有在 python 中修复此错误,'ignore' 将消耗接下来的几个字节以满足长度
during the decoding of an invalid UTF-8 byte sequence, only the
start byte and the continuation byte(s) are now considered invalid, instead of the number of bytes specified by the start byte
问题已修复:
Python 2.6.6 rc1
Python 2.7.1 rc1(以及 2.7 的所有 future 版本)
Python 3.1.3 rc1(以及 3.x 的所有 future 版本)
Python 2.5 及以下版本将包含此问题。
在上面的例子中,"\xef\xbc</name".decode('utf-8', errors='ignore')
应该
返回"</name"
,但在“有漏洞”的 python 版本中,它返回 "/name"
.
前四位 ( 0xe
) 描述了一个 3 字节的 UTF 字符,所以字节 0xef
, 0xbc
,然后(错误地)0x3c
( '<'
) 被消耗。
0x3c
不是一个有效的连续字节,它首先创建了无效的 3 字节 UTF 字符。
python 的固定版本仅删除第一个字节和仅有效的后续 字节,留下0x3c
未消费
关于Python UTF-8 XML 解析 (SUDS) : Removing 'invalid token' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8719330/