2017-05-07 26 views
1

我使用BeautifulSoup解析XML:让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>] 

结果,5位被压缩成1的第一t标签,尽管xml:space="preserve"属性。

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

回答

2

我不能给你一个关于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 '] 
相关问题