gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:00:39 24 4
gpt4 key购买 nike

我想要一个标签的所有子标签,标签之间没有空格。但是 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

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

最佳答案

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 , 你只会得到直接的 child ,而不是 child 的 child 。

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

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)

关于python - BeautifulSoup .children 或 .content 标签之间没有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56021345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com