【问题标题】:How to remove all a href tags from text如何从文本中删除所有 a href 标签
【发布时间】:2013-09-29 17:18:40
【问题描述】:

我有一个脚本来替换“ahref”标签中的单词。但是,我想完全删除 a href,这样您就可以在没有链接的情况下使用 Google 一词。

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中的单词并在它们之前和之后放置一个“”。我不知道该怎么做。我想这是在替换之前完成的。

【问题讨论】:

  • 你可以留下一个毫无意义的&lt;a&gt;吗?你可以del a['href']

标签: python html parsing beautifulsoup


【解决方案1】:

改用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>

更新:

如果你想完全摆脱&lt;a&gt;标签,你可以使用.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>

【讨论】:

  • 谢谢,但我看到的谷歌是链接还是普通文本。另外,我如何在 google 或 href 中的任何单词之前放置一个空格。谢谢
  • 1) 我不知道浏览器是如何在没有href 的情况下呈现&lt;a&gt; 标签的——为什么不自己尝试查看而不是让我进行检查? 2) 我不确定你在问什么。
  • 是的,没有检查任何链接。一旦我得到所有的“”,我想在 之后和 之前放置一个“”。所以你好。应该变成,你好
  • 相应地更新了我的答案。
  • AFAIK,find_all 现在优先于 findAll(后者可用于向后兼容)。
【解决方案2】:

你可以用漂白剂

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 是漂白的文档。

【讨论】:

    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多