相关文章推荐
博学的钢笔  ·  JS得到div ...·  1 月前    · 
焦虑的灯泡  ·  core audio - ...·  1 年前    · 
健壮的山寨机  ·  google chrome - ...·  1 年前    · 
爱喝酒的葫芦  ·  python - ...·  1 年前    · 

使用BeautifulSoup删除一个具有特定类别的div

51 人关注

我想从 soup 对象中删除特定的 div
I am using python 2.7 and bs4 .

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

但这将删除所有的 div 。我怎样才能删除一个具有特定类别的 div

python
python-2.7
beautifulsoup
Riken Shah
Riken Shah
发布于 2015-08-18
4 个回答
lemonhead
lemonhead
发布于 2015-08-18
已采纳
0 人赞同

当然,你可以只 select , find , or find_all 替换代码3】,然后调用 decompose() on those divs.

例如,如果你想删除所有具有 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 . 另见 这个答案
d=div.extract(),如果你想获得被移除的元素作为d,并做一些进一步的工作。
Vineet Kumar Doshi
Vineet Kumar Doshi
发布于 2015-08-18
0 人赞同

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

它是如何工作的呢?你给 a_tag 赋值,然后修改 soup ,但打印 a_tag 。我无法让它工作。
david euler
david euler
发布于 2015-08-18
0 人赞同

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)
    
在BS4中工作得很好。
3ppps
3ppps
发布于 2015-08-18
0 人赞同
    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()