如何从文本中删除所有href标记

时间:2013-09-29 17:18:40

标签: python html parsing beautifulsoup

我有一个脚本来替换“ahref”标签中的单词。但是我想完全删除一个href,这样你就没有链接了。

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>')
for a in soup.findAll('a'):
    a['href'] = a['href'].replace("google", "mysite")
result = str(soup)

你也可以找到放在href中的所有单词并在它们之前和之后放置一个“”。我不知道该怎么做。我想这是在更换之前完成的。

2 个答案:

答案 0 :(得分:8)

使用del a['href'],就像在普通字典上一样:

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>')
for a in soup.findAll('a'):
    del a['href']

给你:

>>> print str(soup)
<p>Hello <a>Google</a></p>

<强>更新

如果您想完全删除<a>代码,可以使用.replaceWithChildren()方法:

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>')
for a in soup.findAll('a'):
    a.replaceWithChildren()

给你:

>>> print str(soup)
<p>Hello Google</p>

...而且,您在评论中要求的内容(用空格包装标签的文本内容)可以通过以下方式实现:

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>')
for a in soup.findAll('a'):
    del a['href']
    a.setString(' %s ' % a.text)

给你:

>>> print str(soup)
<p>Hello <a> Google </a></p>

答案 1 :(得分:5)

您可以使用漂白剂

pip install bleach

然后像这样使用它......

import bleach
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<a href = "somesite.com">hello world</a>')
clean = bleach.clean(soup,tags[],strip=True)

这导致......

>>> print clean
u'hello world'

here 是漂白的文档。