5

私が持っているとしましょう

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

a hrefs と /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 に答える
-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 '

この anwser を参照してください:ダウンロードしたページからすべての html タグを削除する方法

于 2013-09-30T08:22:36.777 に答える