from BeautifulSoup import BeautifulSoup
html = '''<div class="thisText">
Poem <a href="http://famouspoetsandpoems.com/poets/edgar_allan_poe/poems/18848">The Raven</a>Once upon a midnight dreary, while I pondered, weak and weary... </div>
<div class="thisText">
In the greenest of our valleys By good angels tenanted..., part of<a href="http://famouspoetsandpoems.com/poets/edgar_allan_poe/poems/18848">The Haunted Palace</a>
</div>'''
soup = BeautifulSoup(html)
all_poems = soup.findAll("div", {"class": "thisText"})
for poems in all_poems:
print(poems.text)
我有这个示例代码,我找不到如何在删除的标签周围添加空格,所以当 <a href...>
中的文本时格式化它可以阅读并且不会像这样显示:
PoemThe RavenOnce upon a midnight dreary, while I pondered, weak and weary...
In the greenest of our valleys By good angels tenanted..., part ofThe Haunted Palace
最佳答案
beautifoulsoup4
中的
get_text()
有一个名为 separator
的可选输入。您可以按如下方式使用它:
soup = BeautifulSoup(html)
text = soup.get_text(separator=' ')
关于python - 如何在 BeautifulSoup 中删除的标签周围添加空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31140143/