我正在尝试使用 Python 和 BeautifulSoup 4 (bs4) 将 Inkscape SVG 转换为某些专有软件的类似 XML 的格式。我似乎无法让 bs4 正确解析一个最小的示例。我需要解析器尊重自闭标签,处理 unicode,而不是添加 html 内容。我认为用 selfClosingTags 指定“lxml”解析器应该可以做到这一点,但是不行!一探究竟。
#!/usr/bin/python
from __future__ import print_function
from bs4 import BeautifulSoup
print('\nbs4 mangled XML:')
print(BeautifulSoup('<x><c name="b1"><d value="a"/></c></x>',
features = "lxml",
selfClosingTags = ('d')).prettify())
print('''\nExpected output:
<x>
<c name="b1">
<d value="a"/>
</c>
</x>''')
这打印
bs4 mangled XML:
/usr/local/lib/python2.7/dist-packages/beautifulsoup4-4.4.1-py2.7.egg/bs4/__init__.py:112: UserWarning: BS4 does not respect the selfClosingTags argument to the BeautifulSoup constructor. The tree builder is responsible for understanding self-closing tags.
<html>
<body>
<x>
<c name="b1">
<d value="a">
</d>
</c>
</x>
</body>
</html>
Expected output:
<x>
<c name="b1">
<d value="a"/>
</c>
</x>
我已经查看了相关的 StackOverflow 问题,但没有找到解决方案。
这个问题 https://stackoverflow.com/questions/15980757/how-to-prevent-beautifulsoup4-from-adding-extra-htmlbody-tags-to-the-soup解决了 html 样板,但仅用于解析 html 的子部分,而不用于解析 xml。
这个问题 https://stackoverflow.com/questions/4844827/can-beautifulsoup-parse-xml-when-certain-tag-is-self-closing-and-not-at-the-same涉及让 beautifulsoup 4 尊重自关闭标签,并且没有可接受的答案。
这个问题 https://stackoverflow.com/questions/2211589/selfclosingtags-in-beautifulsoup似乎表明传递 selfClosingTags 参数应该有所帮助,但正如您所看到的,这现在会生成一个警告BS4 does not respect the selfClosingTags argument
,并且自闭合标签被破坏。
这个问题 https://stackoverflow.com/questions/14961497/how-to-get-beautifulsoup-4-to-respect-a-self-closing-tag建议使用“xml”(而不是“lxml”)将导致空标签自动关闭。这might适合我的目的,但将“xml”解析器应用于我的实际数据会失败,因为文件包含“xml”解析器不支持的unicode。
“xml”与“lxml”不同吗?标准中是否有“xml”cannot支持unicode和“lxml”cannot包含自闭合标签?也许我只是想做一些被禁止的事情?