【问题标题】:Make BeautifulSoup honor xml:space="preserve"制作 BeautifulSoup 荣誉 xml:space="preserve"
【发布时间】:2023-03-25 12:05:01
【问题描述】:

我正在使用 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" 而不会折叠空格?

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    关于 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  ']
    

    【讨论】:

      猜你喜欢
      • 2013-09-08
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多