【发布时间】:2011-08-01 16:41:20
【问题描述】:
可以使用 BeautifulSoup 从 HTML 中删除 <script> 标记及其所有内容,还是必须使用正则表达式或其他方法?
【问题讨论】:
标签: python html beautifulsoup
可以使用 BeautifulSoup 从 HTML 中删除 <script> 标记及其所有内容,还是必须使用正则表达式或其他方法?
【问题讨论】:
标签: python html beautifulsoup
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<script>a</script>baba<script>b</script>', 'html.parser')
>>> for s in soup.select('script'):
>>> s.extract()
>>> soup
baba
【讨论】:
[s.extract() for s in soup(['iframe', 'script'])] 注意要使用多个标签,参数必须是一个列表
'<script class="blah">a</script>baba<script id="blahhhh">b</script>' 的内容?是一样的吗?
<html><head></head><body><p>baba</p></body></html>
为那些可能需要将来参考的人更新了答案:
正确答案是。
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> 等碎屑非常有用。
【讨论】:
decompose 和extract 的区别在于后者返回被删除的东西,而前者只是销毁它。所以这是对这个问题的更准确的答案,但其他方法确实有效。
i 标签并想要删除所有标签,我们可以(类似于上面的@FábioDiniz extract 示例)执行[s.decompose() for s in soup('i')]。 decompose() 本身只会删除第一个匹配项。
如 (official documentation) 中所述,您可以使用 extract 方法删除与搜索匹配的所有子树。
import BeautifulSoup
a = BeautifulSoup.BeautifulSoup("<html><body><script>aaa</script></body></html>")
[x.extract() for x in a.findAll('script')]
【讨论】:
extract 的特定元素。 [x.extract() for x in a.select('span.className')]