我有一个简单的脚本,我在其中获取 HTML 页面,将其传递给 BeautifulSoup 以删除所有脚本和样式标签,然后我想将 HTML 结果传递给另一个方法。是否有捷径可寻?浏览了一下BeautifulSoup.py,还没看到。
soup = BeautifulSoup(html)
for script in soup("script"):
soup.script.extract()
for style in soup("style"):
soup.style.extract()
contents = soup.html.contents
text = loader.extract_text(contents)
contents = soup.html.contents 只是得到一个列表,所有内容都在类中定义。有没有一种方法可以在 soup 操作之后只返回原始 html?或者我是否只需要浏览 contents
列表并将 html 重新组合在一起,不包括脚本和样式标签?
或者是否有更好的解决方案来完成我想要的?
最佳答案
unicode( soup )
给你 html。
另外你想要的是:
for elem in soup.findAll(['script', 'style']):
elem.extract()
关于python - 使用 BeautifulSoup 去除 html 中的脚本和样式标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3874442/