我想知道如何使用 BeautifulSoup
删除所有 HTML 标签及其内容。
输入:
... text <strong>ha</strong> ... text
输出:
... text ... text
最佳答案
使用replace_with()
(或 replaceWith()
):
from bs4 import BeautifulSoup, Tag
text = "text <strong>ha</strong> ... text"
soup = BeautifulSoup(text)
for tag in soup.find_all('strong'):
tag.replaceWith('')
print soup.get_text()
打印:
text ... text
或者,正如@mata 所建议的,您可以使用 tag.decompose()
而不是 tag.replaceWith('')
- 会产生相同的结果,但看起来更合适。
关于python - 从文本中删除所有 HTML 标签及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18453176/