防止 BeautifulSoup4 用 <html> 和 <body> 标签包装 XML

Prevent BeautifulSoup4 from wrapping XML with <html> and <body> tags

我已经使用 bs4 更改 XML 中某些元素的一些数字字符串,但我不希望 html 或正文标签出现在 XML 中当我将 XML 另存为文件时。

<annotation>
... more stuff here
</annotation>

变成

<html>
<body>
<annotation>
... more stuff here
</annotation>
</body>
</html>

通过

加载后

soup = BeautifulSoup(file_obj.read(), 'lxml')

我想在保存之前美化我的 XML,但现在更容易转换 soup -> string 然后扔掉我不想要的元素。

Link 到我正在使用的一个完整 XML 文件:https://gist.github.com/jtara1/4e583160441976e198aba2c7651aaf70

使用 bs4,您可以将解析器引擎更改为 html.parser:

 soup = BeautifulSoup(file_obj.read(), 'html.parser')