我正在使用 Beautiful Soup 解析 xml 文件,但在解析空元素时发现不一致的行为。即
from BeautifulSoup import BeautifulSoup
s1 = "<c><a /><b /></c>"
s2 = "<c><a></a><b></b></c>"
soup1 = BeautifulSoup(s1)
soup2 = BeautifulSoup(s2)
print soup1
# <c><a><b></b></a></c>
print soup2
# <c><a></a><b></b></c>
请注意,在第一种情况下 b 标记位于 a 标记内,但在第二种情况下则不在。我认为 XML 规范意味着 s1 和 s2 是等价的?
关于如何处理这个问题有什么想法吗?
请您参考如下方法:
anchor 和粗体(<a>,<b>)元素不能自闭,所以这是无效的XHTML。
最重要的是,XHTML spec表示斜杠前必须有一个空格:
Include a space before the trailing / and > of empty elements, e.g. <br />, <hr /> and <img src="karen.jpg" alt="Karen" />. Also, use the minimized tag syntax for empty elements, e.g. <br />, as the alternative syntax <br></br> allowed by XML gives uncertain results in many existing user agents.
