如何用空格替换标签 Beautiful Soup

use*_*753 5 html python beautifulsoup html-parsing

假设我有

text = """ <a href = 'http://www.crummy.com/software'>Hello There</a>"""
Run Code Online (Sandbox Code Playgroud)

我想用一个空格(“”)替换 a hrefs 和 /a 。在它的位置。顺便说一句,它是一个 BeautifulSoup.BeautifulSoup 类。所以正常的 .replace 是行不通的。

我希望文字只是

""" Hello There """
Run Code Online (Sandbox Code Playgroud)

注意“Hello There”前后的空格。

ale*_*cxe 7

您可以使用replaceWith()(或replace_with()):

from bs4 import BeautifulSoup

soup = BeautifulSoup("""
<html>
 <body>
  <a href = 'http://www.crummy.com/software'>Hello There</a>
 </body>
</html>
""")

for a in soup.findAll('a'):
    a.replaceWith(" %s " % a.string)

print soup
Run Code Online (Sandbox Code Playgroud)

印刷:

<html><body>
 Hello There 
</body></html>
Run Code Online (Sandbox Code Playgroud)