5

假设我有

text = """ <a href = 'http://www.crummy.com/software'>Hello There</a>"""

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

我希望文字只是

""" Hello There """

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

4

3 回答 3

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

印刷:

<html><body>
 Hello There 
</body></html>
于 2013-09-30T08:22:08.637 回答
4

使用.replace_with().text属性:

>>> from bs4 import BeautifulSoup as BS
>>> text = """ <a href = 'http://www.crummy.com/software'>Hello There</a>"""
>>> soup = BS(text)
>>> mytag = soup.find('a')
>>> mytag.replace_with(mytag.text + ' ')
<a href="http://www.crummy.com/software">Hello There</a>
>>> print soup
 Hello There 
于 2013-09-30T08:33:43.467 回答
-1
 import re
 notag = re.sub("<.*?>", " ", html)
 >>> text = """ <a href = 'http://www.crummy.com/software'>Hello There</a>"""
 >>> notag = re.sub("<.*?>", " ", text)
 >>> notag
 '  Hello There '

请参阅此答案:如何从下载的页面中删除所有 html 标记

于 2013-09-30T08:22:36.777 回答