Beautifulsoup分解()

Gil*_*ert 5 python beautifulsoup python-3.x

我正试图<script>利用beatifulsoup 摆脱标签和标签内的内容.我去了文档,似乎是一个非常简单的函数来调用.有关功能的更多信息这里.这是我到目前为止解析的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>
Run Code Online (Sandbox Code Playgroud)

想象一下,你有一些这样的网页内容,你在一个名为的BeautifulSoup对象中有这样的内容soup_html.如果我运行soup_html.script.decompose()并且他们调用该对象soup_html,脚本标签仍然存在.我如何摆脱<script>这些标签内的内容?

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

soup.script.decompose()

html_body
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 8

soup.script.decompose()

这将仅从"Soup"中删除单个脚本元素.相反,我认为你的意思是分解所有这些:

for script in soup("script"):
    script.decompose()
Run Code Online (Sandbox Code Playgroud)


InT*_*ell 7

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

selects = soup.findAll('select')
for match in selects:
    match.decompose()
Run Code Online (Sandbox Code Playgroud)