Deleting a div with a particlular class using BeautifulSoup

后端 未结 4 1097
难免孤独
难免孤独 2020-12-09 02:02

I want to delete the specific div from soup object.
I am using python 2.7 and bs4.

According to documentati

相关标签:
4条回答
  • 2020-12-09 02:24

    This will help you:

    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
    

    Output:

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

    Let me know if it helps

    0 讨论(0)
  • 2020-12-09 02:28
        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>
    
    0 讨论(0)
  • 2020-12-09 02:30

    Sure, you can just select, find, or find_all the divs of interest in the usual way, and then call decompose() on those divs.

    For instance, if you want to remove all divs with class sidebar, you could do that with

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

    If you want to remove a div with a specific id, say main-content, you can do that with

    soup.find('div', id="main-content").decompose()
    
    0 讨论(0)
  • 2020-12-09 02:35

    Hope it help:

    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)
    
    0 讨论(0)
提交回复
热议问题