使用来自 python 2.7.6 的 bs4 解析此示例文档:
<html>
<body>
<p>HTML allows omitting P end-tags.
<p>Like that and this.
<p>And this, too.
<p>What happened?</p>
<p>And can we <p>nest a paragraph, too?</p></p>
</body>
</html>
使用:
from bs4 import BeautifulSoup as BS
...
tree = BS(fh)
很长一段时间以来,HTML 都允许省略各种元素类型的结束标记,包括 P(检查架构或解析器)。但是,本文档中 bs4 的 prettify() 表明它在看到 </body> 之前不会结束任何这些段落:
<html>
<body>
<p>
HTML allows omitting P end-tags.
<p>
Like that and this.
<p>
And this, too.
<p>
What happened?
</p>
<p>
And can we
<p>
nest a paragraph, too?
</p>
</p>
</p>
</p>
</p>
</body>
这不是 prettify() 的错,因为手动遍历树我得到了相同的结构:
<[document]>
<html>
␊
<body>
␊
<p>
HTML allows omitting P end-tags.␊␊
<p>
Like that and this.␊␊
<p>
And this, too.␊␊
<p>
What happened?
</p>
␊
<p>
And can we
<p>
nest a paragraph, too?
</p>
</p>
␊
</p>
</p>
</p>
</body>
␊
</html>
␊
</[document]>
现在,这将是 XML 的正确结果(至少到 </body>,此时它应该报告 WF 错误)。但这不是 XML。是什么赋予了?