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

POPMUISE
TA贡献1765条经验 获得超5个赞
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<script>a</script>baba<script>b</script>', 'lxml')
>>> [s.extract() for s in soup('script')]
>>> soup
baba

慕哥9229398
TA贡献1877条经验 获得超6个赞
为可能需要将来参考的人员更新了答案:正确答案是。 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>'
消除诸如“ script”,“ img”之类的碎屑非常有用。

素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
如(官方文档)中所述,您可以使用extract方法删除与搜索匹配的所有子树。
import BeautifulSoup
a = BeautifulSoup.BeautifulSoup("<html><body><script>aaa</script></body></html>")
[x.extract() for x in a.findAll('script')]
- 3 回答
- 0 关注
- 1018 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消