Skip to main content
 首页 » 编程设计

python之让 BeautifulSoup 荣誉 xml :space ="preserve"

2024年10月01日9java哥

我正在使用 BeautifulSoup 来解析 XML:

In [64]: b = bs4.BeautifulSoup('<xml><t xml:space="preserve">     </t><t xml:space="preserve">  A  </t></xml>', 'xml') 
In [65]: b.find_all('t') 
Out[65]: [<t xml:space="preserve"> </t>, <t xml:space="preserve">  A  </t>] 

因此,尽管有 xml:space="preserve" 属性,第一个 t 标记中的 5 个空格被折叠成 1 个。

有没有办法让 BeautifulSoup 尊重 xml:space="preserve" 而不是折叠空格?

请您参考如下方法:

关于 BeautifulSoup,我无法直接回答您。但是,lxml 可以为您做到这一点。

>>> from lxml import etree 
>>> tree = etree.fromstring('<xml><t xml:space="preserve">     </t><t xml:space="preserve">  A  </t></xml>') 
>>> [_.text for _ in tree.findall('t')] 
['     ', '  A  ']