2017-05-07 57 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 ']