BeautifulSoup .children 或 .content 标签之间没有空格

2024-02-07

我希望标签的所有子标签之间没有空格。但美丽的汤.contents and .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 仅返回标签并忽略空格?

文档 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children对这个话题不是很有帮助。示例中的 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 - 摆脱段落空白/换行符 https://stackoverflow.com/questions/24558075/beautifulsoup-getting-rid-of-paragraph-whitespace-line-breaks

从 python BeautifulSoup 的输出中删除新行 '\n' https://stackoverflow.com/questions/22890807/removing-new-line-n-from-the-output-of-python-beautifulsoup

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

另一个例子:

使用 Beautifulsoup 的带有空格的类的正则表达式 https://stackoverflow.com/questions/38824121/regular-expression-for-class-with-whitespaces-using-beautifulsoup

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


美丽汤有.find_all(True) https://www.crummy.com/software/BeautifulSoup/bs4/doc/#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))

Prints:

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

结合recursive=False https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument,并且您只能得到直系子代,而不能得到子代的子代。

为了演示我添加了<b>给第二个孩子。这将是一个孙子。

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))

with recursive=False它打印:

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

with recursive=True它打印:

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

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

为什么 BeautifulSoup .children 包含无名元素以及预期标签 https://stackoverflow.com/questions/18284524/why-does-beautifulsoup-children-contain-nameless-elements-as-well-as-the-expect

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

BeautifulSoup .children 或 .content 标签之间没有空格 的相关文章

随机推荐