python - 如何在 BeautifulSoup 中删除的标签周围添加空间

标签 python html beautifulsoup html-parsing

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/

相关文章:

javascript - 我可以获得访客的路由器名称或 MAC 地址吗?

python - 如何使用 Python 将 URL 中的所有文本复制到剪贴板?

python - 在迭代多个 for 循环时创建字典?

python - Python 中的逐像素数据

python - 突破递归函数?

css - 如何在 HTML 中创建面板

python - 从 csv 文件中的 url 检索数据 - Python

python - 为什么我不能在 pandas 中将列分成两列?

python - 保存一个 numpy 矩阵

javascript - Div 动画不会向下平移