如何用空白替换文本中提取的 HTML 标签?

How to replace extracted HTML tags in a text with a blank?

我正在从没有所有标签的 html 页面中提取文本(使用 Python 和 BeautifulSoup)。但是,标签不会替换为空白。因此,例如,对于 "blah blahDIVTAGblah",我得到以下文本 "blah blahblah"。如何在第二个和第三个 blah 之间插入一个空格?我正在使用以下代码。

# kill all script and style elements
    for script in soup(["script", "style"]):
        script.extract()

代码来自BeautifulSoup Grab Visible Webpage Text

您可以使用 .replace_with() 简单地将标签替换为空白:

for script in soup(["script", "style"]):
    script.replace_with(" ")