我希望标签的所有子标签之间没有空格。但美丽的汤.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
这个问题是关于类属性中的空格。