【发布时间】: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