我可以使用BeautifulSoup删除脚本标签吗?

时间:2011-04-08 17:14:32

标签: python html beautifulsoup

可以使用BeautifulSoup从HTML中删除脚本标记及其所有内容,还是必须使用正则表达式或其他内容?

3 个答案:

答案 0 :(得分:136)

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<script>a</script>baba<script>b</script>', 'lxml')
>>> [s.extract() for s in soup('script')]
>>> soup
baba

答案 1 :(得分:22)

为可能需要以后参考的人更新了答案: 正确的答案是。 decompose() 您可以使用不同的方式,但decompose就地工作。

使用示例:

soup = BeautifulSoup('<p>This is a slimy text and <i> I am slimer</i></p>')
soup.i.decompose()
print str(soup)
#prints '<p>This is a slimy text and</p>'

非常有用的摆脱碎屑,如脚本&#39;,&#39; img&#39;某某等等。

答案 2 :(得分:20)

如(official documentation)中所述,您可以使用extract方法删除与搜索匹配的所有子树。

import BeautifulSoup
a = BeautifulSoup.BeautifulSoup("<html><body><script>aaa</script></body></html>")
[x.extract() for x in a.findAll('script')]