【问题标题】:Deleting a div with a particlular class using BeautifulSoup使用 BeautifulSoup 删除具有特定类的 div
【发布时间】:2015-11-10 21:25:31
【问题描述】:

我想从soup 对象中删除特定的div
我正在使用python 2.7bs4

根据文档,我们可以使用div.decompose()

但这会删除所有div。如何删除具有特定类的div

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    当然,您可以按照通常的方式只 selectfindfind_all 感兴趣的 divs,然后在这些 div 上调用 decompose()

    例如,如果你想删除所有类 sidebar 的 div,你可以这样做

    # replace with `soup.findAll` if you are using BeautifulSoup3
    for div in soup.find_all("div", {'class':'sidebar'}): 
        div.decompose()
    

    如果您想删除具有特定 id 的 div,例如 main-content,您可以使用

    soup.find('div', id="main-content").decompose()
    

    【讨论】:

    • 简短而精确。谢谢!
    • @lemonhead 你知道如何在分解的位置放置替换文本吗?
    • @CodeGuru 在这种情况下你不会分解,你会选择/找到元素然后调用elem.string.replace_with。另见this answer
    • d=div.extract() 如果你想将移除的元素作为 d 获取,并做进一步的事情。
    【解决方案2】:

    这将对您有所帮助:

    from bs4 import BeautifulSoup
    
    markup = '<a>This is not div <div class="1">This is div 1</div><div class="2">This is div 2</div></a>'
    soup = BeautifulSoup(markup,"html.parser")
    a_tag = soup
    
    soup.find('div',class_='2').decompose()
    
    print a_tag
    

    输出:

    <a>This is not div <div class="1">This is div 1</div></a>
    

    如果有帮助请告诉我

    【讨论】:

    • 它是如何工作的?您为a_tag 分配了一个值,然后修改了soup,但打印了a_tag。?我无法让它工作。
    【解决方案3】:

    希望对您有所帮助:

    from bs4 import BeautifulSoup
    from bs4.element import Tag
    
    markup = '<a>This is not div <div class="1">This is div 1</div><div class="2">This is div 2</div></a>'
    soup = BeautifulSoup(markup,"html.parser")
    
    for tag in soup.select('div.1'):
      tag.decompose()
    
    print(soup)
    

    【讨论】:

    • 在 BS4 中像魅力一样工作。
    【解决方案4】:
        from BeautifulSoup import BeautifulSoup
        >>> soup = BeautifulSoup('<body><div>1</div><div class="comment"><strong>2</strong></div></body>')
        >>> for div in soup.findAll('div', 'comment'):
        ...   div.extract()
        ... 
        <div class="comment"><strong>2</strong></div>
        >>> soup
        <body><div>1</div></body>
    

    【讨论】:

    • 提取函数不会从原始汤中删除 div。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多