解决lxml报错invalid character in attribute value

发布于 / Python / 0 条评论

使用Python的lxml解析一个xml文件,始终报错:xml.parsers.expat.ExpatError: not well-formed (invalid token): line xxx, column xxx

这是因为xml文件内含有一些特殊字符。使用010editor看一下:

image.png

这里的0x22 0x1F 0xEF 0xBF 0xBD 0x08一串就是lxml无法解析的字符。

困惑了好久,使用了https://gist.github.com/lawlesst/4110923里提供的方法:data_str.encode('utf-8', 'xmlcharrefreplace')以及转utf8再转gbk均无效。

通过大量实验,找到了唯一有效的一个办法:

# 删除lxml无法解析的特殊字符和unicode字符
xml_str = re.sub(u"[\x00-\x08\x0b-\x0c\x0e-\x1f]+", u"", xml_str )
xml_str = re.sub('[^\x00-\x7F]', '', xml_str )

转载原创文章请注明,转载自: 斐斐のBlog » 解决lxml报错invalid character in attribute value
目前还没有评论,快来抢沙发吧~