【问题标题】:Preserve space when stripping HTML with Beautiful Soup使用 Beautiful Soup 剥离 HTML 时保留空间
【发布时间】:2011-08-16 01:50:46
【问题描述】:
from BeautifulSoup import BeautifulSoup

html = "<html><p>Para 1. Words</p><p>Merge. Para 2<blockquote>Quote 1<blockquote>Quote 2</p></html>"
print html
soup = BeautifulSoup(html)
print u''.join(soup.findAll(text=True))

这段代码的输出是“Para 1 WordsMerge.Para 2Quote 1Quote 2”。

我不希望第一段的最后一个词与第二段的第一个词合并。 例如。 “第 1 段单词合并。第 2 段引用 1 引用 2”。 这可以使用 BeautifulSoup 库来实现吗?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    如果您在 4.x 版本中使用 get_text()

    from bs4 import BeautifulSoup
    ...
    ...
    soup.get_text(" ")
    

    【讨论】:

      【解决方案2】:

      只需用空格连接各个部分:

      print u' '.join(soup.findAll(text=True))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多