【发布时间】:2016-07-08 17:43:07
【问题描述】:
我正在尝试使用 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 问题,但没有找到解决方案。
This question 处理 html 样板,但仅用于解析 html 的子部分,而不用于解析 xml。
This question 与让 beautifulsoup 4 尊重自闭合标签有关,并且没有可接受的答案。
This question 似乎表明传递 selfClosingTags 参数应该会有所帮助,但正如您所看到的,现在这会生成警告 BS4 does not respect the selfClosingTags argument,并且自关闭标签被破坏。
This question 建议使用“xml”(而不是“lxml”)会导致空标签自动关闭。这可能适用于我的目的,但将“xml”解析器应用于我的实际数据失败,因为文件包含 unicode,而“xml”解析器不支持。
“xml”和“lxml”有区别吗,标准中“xml”不能支持unicode,“lxml”不能包含自闭标签?也许我只是想做一些被禁止的事情?
【问题讨论】:
-
“因为文件包含 unicode,“xml”解析器不支持”→ 不,XML 解析器根据定义支持 Unicode。您应该发布一个关于如何打开和写入文件的最小示例。
-
为什么不使用 lxml 本身?
标签: python xml unicode beautifulsoup bs4