如何让Python bs4在XML上正常工作?

2024-04-28

我正在尝试使用 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包含自闭合标签?也许我只是想做一些被禁止的事情?


如果您希望结果输出为xml然后将其解析为这样。你的xml数据可以包含unicode,但是,您需要声明编码:

#!/usr/bin/env python
# -*- encoding: utf8 -*-

The SelfClosingTags不再被认可 http://www.crummy.com/software/BeautifulSoup/bs4/doc/#xml。相反,Beautifulsoup 将空标签视为空元素标签。如果将子级添加到空元素标记,它就不再是空元素标记。

将您的函数更改为如下所示应该可以工作(除了编码之外):

print(BeautifulSoup('<x><c name="b1"><d value="a®"/></c></x>',
    features = "xml").prettify())

Result:

<?xml version="1.0" encoding="utf-8"?>
<x>
 <c name="b1">
  <d value="aÂŽ"/>
 </c>
</x>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让Python bs4在XML上正常工作? 的相关文章

随机推荐