Beautifulsoup 分解()

新手上路,请多包涵

我正在尝试使用 beatifulsoup 摆脱 <script> 标签和标签内的内容。我去看了文档,似乎是一个非常简单的调用函数。有关该功能的更多信息,请参见 此处。这是我到目前为止解析的 html 页面的内容……

 <body class="pb-theme-normal pb-full-fluid">
    <div class="pub_300x250 pub_300x250m pub_728x90 text-ad textAd text_ad text_ads text-ads text-ad-links" id="wp-adb-c" style="width: 1px !important;
    height: 1px !important;
    position: absolute !important;
    left: -10000px !important;
    top: -1000px !important;
    ">
</div>
<div id="pb-f-a">
</div>
    <div class="" id="pb-root">
    <script>
    (function(a){
        TWP=window.TWP||{};
        TWP.Features=TWP.Features||{};
        TWP.Features.Page=TWP.Features.Page||{};
        TWP.Features.Page.PostRecommends={};
        TWP.Features.Page.PostRecommends.url="https://recommendation-hybrid.wpdigital.net/hybrid/hybrid-filter/hybrid.json?callback\x3d?";
        TWP.Features.Page.PostRecommends.trackUrl="https://recommendation-hybrid.wpdigital.net/hybrid/hybrid-filter/tracker.json?callback\x3d?";
        TWP.Features.Page.PostRecommends.profileUrl="https://usersegment.wpdigital.net/usersegments";
        TWP.Features.Page.PostRecommends.canonicalUrl=""
    })(jQuery);

    </script>
    </div>
</body>

想象一下,您有一些类似的 Web 内容,并且将其保存在名为 soup_html 的 BeautifulSoup 对象中。如果我运行 soup_html.script.decompose() 并且他们调用对象 soup_html 脚本标签仍然存在。我如何摆脱 <script> 以及这些标签中的内容?

 markup = 'The html above'
soup = BeautifulSoup(markup)
html_body = soup.body

soup.script.decompose()

html_body

原文由 redeemefy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 622
2 个回答

soup.script.decompose()

这只会从“Soup”中删除一个 _脚本元素_。相反,我认为你打算分解所有这些:

 for script in soup("script"):
    script.decompose()

原文由 alecxe 发布,翻译遵循 CC BY-SA 3.0 许可协议

为了详细说明 alecxe 提供的答案,这里有一个完整的脚本供任何人参考:

 selects = soup.findAll('select')
for match in selects:
    match.decompose()

原文由 InTheShell 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题