【问题标题】:How to remove whitespace in BeautifulSoup如何在 BeautifulSoup 中删除空格
【发布时间】:2011-05-15 07:39:52
【问题描述】:

我有一堆 HTML 正在用 BeautifulSoup 进行解析,除了一个小问题外,它运行良好。我想将输出保存为单行字符串,并将以下内容作为我当前的输出:

    <li><span class="plaincharacterwrap break">
                    Zazzafooky but one two three!
                </span></li>
<li><span class="plaincharacterwrap break">
                    Zazzafooky2
                </span></li>
<li><span class="plaincharacterwrap break">
                    Zazzafooky3
                </span></li>

理想情况下我会喜欢

<li><span class="plaincharacterwrap break">Zazzafooky but one two three!</span></li><li><span class="plaincharacterwrap break">Zazzafooky2</span></li>

我想删除很多多余的空格,但不一定可以使用strip() 删除,我也不能公然删除所有空格,因为我需要保留文本。我该怎么做? regex 似乎是一个很常见的问题,但这是唯一的方法吗?

我没有任何&lt;pre&gt; 标记,所以我可以在那里更有力一点。

再次感谢!

【问题讨论】:

  • 如何打印输出?
  • 您可以做浏览器所做的事情:将所有相邻的空白(在文本中)折叠成单个空格。

标签: python regex html-parsing beautifulsoup


【解决方案1】:

以下是不使用正则表达式的方法:

>>> html = """    <li><span class="plaincharacterwrap break">
...                     Zazzafooky but one two three!
...                 </span></li>
... <li><span class="plaincharacterwrap break">
...                     Zazzafooky2
...                 </span></li>
... <li><span class="plaincharacterwrap break">
...                     Zazzafooky3
...                 </span></li>
... """
>>> html = "".join(line.strip() for line in html.split("\n"))
>>> html
'<li><span class="plaincharacterwrap break">Zazzafooky but one two three!</span></li><li><span class="plaincharacterwrap break">Zazzafooky2</span></li><li><span class="plaincharacterwrap break">Zazzafooky3</span></li>'

【讨论】:

    【解决方案2】:

    老问题,我知道,但是 beautifulsoup4 有一个叫做 stripped_strings 的助手。

    试试这个:

    description_el = about.find('p', { "class": "description" })
    descriptions = list(description_el.stripped_strings)
    description = "\n\n".join(descriptions) if descriptions else ""
    

    【讨论】:

      【解决方案3】:
      re.sub(r'[\ \n]{2,}', '', yourstring)
      

      Regex [\ \n]{2} 匹配两个或多个以上的换行符和空格(必须转义)。更彻底的实现是这样的:

      re.sub('\ {2,}', '', yourstring)
      re.sub('\n*', '', yourstring)
      

      我认为第一个只会替换多个换行符,但它似乎(至少对我来说)工作得很好。

      【讨论】:

        【解决方案4】:

        如果你在被 BeautifulSoup prettify() 困扰后来到这里。我认为这个解决方案不会添加额外的空格。

        from lxml import html, etree
        
        doc = html.fromstring(open('inputfile.html').read())
        out = open('out.html', 'wb')
        out.write(etree.tostring(doc))
        

        请看这个Ian Bicking's answer on stackoverflow

        通过 xml.etree 解析很简单...

        from xml.etree import ElementTree as ET
        tree = ET.parse('out.html')
        title = tree.find(".//title").text
        print(title)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-17
          • 1970-01-01
          • 1970-01-01
          • 2011-08-09
          • 2018-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多