【问题标题】:BeautifulSoup how can I remove div element from h1 tagBeautifulSoup 如何从 h1 标签中删除 div 元素
【发布时间】:2021-10-31 10:50:38
【问题描述】:

我已经使用 BeautifulSoup 尝试了下面的解析器 html 代码。

item_detail_soup = BeautifulSoup(html, "html.parser")
h1 = item_detail_soup.find("h1")

我的 H1 解析器输出是:

<h1>
<div class="brand" style="display: block; font-size: 0.75rem;">Apple(#34567)</div>
〔NEW〕 iPhone12 256GB </h1>

我正在尝试删除这个类名为 brand 的 div。

我想要的输出:

<h1> (NEW) iPhone12 256GB </h1>

我已经尝试通过 extract() 然后替换,但我失败了。

h1 = item_detail_soup.find("h1")
h1 = h1.replace(item_detail_soup.find("h1").div.extract(),'')

我怎样才能得到我想要的输出?

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    好消息,您走在正确的轨道上 - 为了实现您的目标,您也可以使用 .extract().replace_with().decompose()

    提取与分解有什么区别?

    .extract() 从树中删除标签或字符串并将其返回/保留为附加的解析树,decompose() 从树中删除标签并完全销毁它及其内容。

    出了什么问题?

    您无法获得预期结果的原因是,您尝试对您的 h1 变量进行操作,因此它始终为空 (.decompose()) 或将包含提取的 tag (.extract()) .

    如何解决?

    首先选择您想要从树中移除的tag,将其移除,然后选择您的&lt;h1&gt; 以查看结果。

    示例(item_detail_soup 中只有一个带有 class 品牌的 div)

    from bs4 import BeautifulSoup
    
    html = '''<h1><div class="brand" style="display: block; font-size: 0.75rem;">Apple(#34567)</div>〔NEW〕 iPhone12 256GB </h1>'''
    item_detail_soup = BeautifulSoup(html, 'html.parser')
    
    item_detail_soup.select_one('div.brand').extract() 
    h1 = item_detail_soup.find('h1')
    

    示例(item_detail_soup 中有多个具有类品牌的 div)

    请注意,您一次只能使用一个选项,因此我将其他选项注释掉。

    from bs4 import BeautifulSoup
    
    html = '''<h1><div class="brand" style="display: block; font-size: 0.75rem;">Apple(#34567)</div>〔NEW〕 iPhone12 256GB </h1>'''
    item_detail_soup = BeautifulSoup(html, 'lxml')
    for item in item_detail_soup.select('div.brand'):
        item.extract()
        #item.decompose()
        #item.replace_with('')
        
    item_detail_soup.h1
    

    输出

    <h1>〔NEW〕 iPhone12 256GB </h1>
    

    【讨论】:

      【解决方案2】:

      试试这个

      item_detail_soup = BeautifulSoup(html, "html.parser")
      for div in item_detail_soup .find_all("div", {'class':'brand'}): 
          div.decompose()
      h1 = item_detail_soup.find("h1")
      

      【讨论】:

        猜你喜欢
        • 2013-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 2019-08-26
        • 1970-01-01
        相关资源
        最近更新 更多