【问题标题】:BeautifulSoup: do not add spaces where they matter, remove them where they don'tBeautifulSoup:不要在重要的地方添加空格,在不重要的地方删除它们
【发布时间】:2014-08-26 20:10:39
【问题描述】:

这个示例 python 程序:

document='''<p>This is <i>something</i>, it happens
               in <b>real</b> life</p>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(document)
print(soup.prettify())

产生以下输出:

<html>
 <body>
  <p>
   This is
   <i>
    something
   </i>
   , it happens
               in
   <b>
    real
   </b>
   life
  </p>
 </body>
</html>

这是错误的,因为它在每个开始和结束标记之前和之后添加空格,例如,&lt;/i&gt;, 之间不应有空格。我希望它:

  1. 不要在没有空格的地方添加空格(即使在块级标签周围,如果它们在 CSS 中使用 display:inline 设置样式,它们也可能会出现问题。)

  2. 将所有空格折叠到一个空格中,可选的换行除外。

类似这样的:

<html>
 <body>
  <p>This is
   <i>something</i>,
   it happens in
   <b>real</b> life</p>
 </body>
</html>

BeautifulSoup 可以做到这一点吗?还有其他推荐的 HTML 解析器可以处理这个吗?

【问题讨论】:

标签: python html beautifulsoup


【解决方案1】:

由于.prettify习惯将每个标签放在自己的行中,不适合生产代码;它仅可用于调试输出,IMO。只需使用 str 内置函数将您的汤转换为字符串。

您想要的是更改树中的字符串内容;您可以创建一个函数来查找包含两个或多个空格字符序列的所有元素(使用预编译的正则表达式),然后替换它们的内容。

顺便说一句,如果您像这样编写示例,您可以让 Python 避免插入无关紧要的空格:

document = ('<p>This is <i>something</i>, it happens '
            'in <b>real</b> life</p>')

这样你就有了两个隐式连接的文字。

【讨论】:

    【解决方案2】:

    Beautiful Soup 的.prettify() 方法被定义为在自己的行上输出每个标签(http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html#pretty-printing)。如果你想要别的东西,你需要自己通过分析树来完成。

    【讨论】:

      【解决方案3】:

      正如之前的 cmets 和 thebjorn 所说,BeautifulSoup 对漂亮 html 的定义是每个标签都在它自己的行上,但是,为了处理您的一些间距问题,例如,您可以先折叠它,如下所示:

      from bs4 import BeautifulSoup
      
      document = """<p>This is <i>something</i>, it happens
                     in <b>real</b> life</p>"""
      
      document_stripped = " ".join(l.strip() for l in document.split("\n"))
      
      soup = BeautifulSoup(document_stripped).prettify()
      
      print(soup)
      

      哪个输出这个:

      <html>
       <body>
        <p>
         This is
         <i>
          something
         </i>
         , it happens in
         <b>
          real
         </b>
         life
        </p>
       </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        • 1970-01-01
        • 2014-03-19
        相关资源
        最近更新 更多