【问题标题】:How to remove surplus tags from beautiful soup result如何从漂亮的汤结果中删除多余的标签
【发布时间】:2018-04-05 15:02:04
【问题描述】:

我只想获取

标签中的内容并删除多余的 div 标签。
我的代码是:

page = """
<p style="text-align: justify">content that I want
    <div ><!-- /316485075/agk_116000_pos_3_sidebar_mobile -->
        <div id="agk_116000_pos_3_sidebar_mobile">
            <script>
                script code
            </script>
        </div>
        <div class="nopadding clearfix hidden-print">
            <div align="center" class="col-md-12">
            <!-- /316485075/agk_116000_pos_4_conteudo_desktop -->
                <div id="agk_116000_pos_4_conteudo_desktop" style="height:90px; width:728px;">
                    <script>
                        script code
                    </script>
                </div>
            </div>
        </div>
    </div>
</p>
"""
soup = BeautifulSoup(page, 'html.parser')
p = soup.find_all('p', {'style' : 'text-align: justify'})

我只想获取字符串 &lt;p&gt;content that I want&lt;/p&gt; 并删除所有 div

【问题讨论】:

标签: python regex python-3.x beautifulsoup


【解决方案1】:

您可以使用replace_with() 函数删除标签及其内容。

soup = BeautifulSoup(html, 'html.parser')   # html is HTML you've provided in question
soup.find('div').replace_with('')
print(soup)

输出:

<p style="text-align: justify">content that I want

</p>

注意:我在这里使用soup.find('div'),因为所有不需要的标签都在第一个div 标签内。因此,如果您删除该标签,则所有其他标签都将被删除。但是,如果您想删除格式不是这样的 HTML 中除p 标签之外的所有标签,则必须使用此:

for tag in soup.find_all():
    if tag.name == 'p':
        continue
    tag.replace_with('')

相当于:

[tag.replace_with('') for tag in soup.find_all(lambda t: t.name != 'p')]

如果你只是想要content that I want 文本,你可以使用这个:

print(soup.find('p').contents[0])
# content that I want

【讨论】:

  • 但是如果我在

    标签内有一个 标签,它只会返回这些标签()之前的字符串

  • 你的说法有点含糊。您可以在问题中添加这样的示例以及预期的输出吗?
【解决方案2】:

捕获组 2 包含您的内容&lt;(.*?)(?:\s.+?&gt;)(.*?)&lt;/\1[&gt;]?

https://regex101.com/r/m8DQic/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 2015-05-03
    • 2016-06-02
    • 2019-09-06
    • 2013-04-26
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多