【问题标题】:Getting html stripped of script and style tags with BeautifulSoup?使用 BeautifulSoup 去除 html 的脚本和样式标签?
【发布时间】:2011-04-21 22:14:22
【问题描述】:

我有一个简单的脚本,我在其中获取 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 拼凑在一起,不包括脚本和样式标签?

或者有没有更好的解决方案来完成我想要的?

【问题讨论】:

    标签: python html-parsing beautifulsoup python-2.6


    【解决方案1】:

    unicode( soup ) 为您提供 html。

    你想要的是这个:

    for elem in soup.findAll(['script', 'style']):
        elem.extract()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2014-10-02
      • 2011-03-31
      • 1970-01-01
      • 2011-05-04
      相关资源
      最近更新 更多