【问题标题】:BeautifulSoup .children or .content without whitespace between tagsBeautifulSoup .children 或 .content 标签之间没有空格
【发布时间】:2019-05-07 11:14:15
【问题描述】:

我希望标签的所有子标签之间没有空格。但是 BeautifulSoups .contents.children 也会返回标签之间的空格。

from bs4 import BeautifulSoup
html = """
<div id="list">
  <span>1</span>
  <a href="2.html">2</a>
  <a href="3.html">3</a>
</div>
"""
soup = BeautifulSoup(html, 'html.parser')
print(soup.find(id='list').contents)

打印出来:

['\n', <span>1</span>, '\n', <a href="2.html">2</a>, '\n', <a href="3.html">3</a>, '\n']

同理

print(list(soup.find(id='list').children))

我想要什么:

[<span>1</span>, <a href="2.html">2</a>, <a href="3.html">3</a>]

有没有办法告诉 BeautifulSoup 只返回标签而忽略空格?

The documentation 在这个话题上不是很有帮助。示例中的 html 标签之间不包含任何空格。

确实去除标签之间所有空格的html解决了我的问题:

html = """<div id="list"><span>1</span><a href="2.html">2</a><a href="3.html">3</a></div>"""

使用这个 html,我得到了标签之间没有空格的标签,因为标签之间没有空格。但我希望使用 BeautifoulSoup,这样我就不必在 html 源代码中乱七八糟了。我希望 BeautifulSoup 能为我做到这一点。

另一种解决方法可能是:

print(list(filter(lambda t: t != '\n', soup.find(id='list').contents)))

但这似乎很不稳定。空格是否保证总是准确的'\n'


给重复标记旅的说明:

有很多关于 BeautifulSoup 和空白的问题。大多数人都在询问如何从“渲染文本”中删除空格。

例如:

BeautifulSoup - getting rid of paragraph whitespace/line breaks

Removing new line '\n' from the output of python BeautifulSoup

两个问题都希望文本没有空格。我想要没有空格的标签。那里的解决方案不适用于我的问题。

另一个例子:

Regular expression for class with whitespaces using Beautifulsoup

这个问题是关于类属性中的空格。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    BeautifulSoup 有 .find_all(True),它返回所有标签,标签之间没有空格:

    from bs4 import BeautifulSoup
    html = """
    <div id="list">
      <span>1</span>
      <a href="2.html">2</a>
      <a href="3.html">3</a>
    </div>
    """
    soup = BeautifulSoup(html, 'html.parser')
    print(soup.find(id='list').find_all(True))
    

    打印:

    [<span>1</span>, <a href="2.html">2</a>, <a href="3.html">3</a>]
    

    recursive=False结合,你只会得到直接的孩子,而不是孩子的孩子。

    为了证明我给第二个孩子添加了&lt;b&gt;。这将是一个孙子。

    from bs4 import BeautifulSoup
    html = """
    <div id="list">
      <span>1</span>
      <a href="2.html"><b>2</b></a>
      <a href="3.html">3</a>
    </div>
    """
    soup = BeautifulSoup(html, 'html.parser')
    print(soup.find(id='list').find_all(True, recursive=False))
    

    使用recursive=False 打印:

    [<span>1</span>, <a href="2.html"><b>2</b></a>, <a href="3.html">3</a>]
    

    使用recursive=True 打印:

    [<span>1</span>, <a href="2.html"><b>2</b></a>, <b>2</b>, <a href="3.html">3</a>]
    

    琐事:现在我有了解决方案,我在 StackOverflow 中发现了另一个看似无关的问题和答案,其中解决方案隐藏在评论中:

    Why does BeautifulSoup .children contain nameless elements as well as the expected tag(s)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-19
      • 2011-08-09
      • 1970-01-01
      • 2023-04-04
      • 2021-09-28
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多