使用BeautifulSoup删除带有特定类的div [英] Deleting a div with a particlular class using BeautifulSoup
问题描述
我想从soup
对象中删除特定的div
.
我正在使用python 2.7
和bs4
.
I want to delete the specific div
from soup
object.
I am using python 2.7
and bs4
.
根据文档,我们可以使用div.decompose()
.
According to documentation we can use div.decompose()
.
但是这将删除所有的div
.如何删除具有特定类别的div
?
But that would delete all the div
. How can I delete a div
with specific class?
推荐答案
当然,您可以 select
, find
或 find_all
div
按常规方式感兴趣,然后调用 decompose()
在这些div上.
Sure, you can just select
, find
, or find_all
the div
s of interest in the usual way, and then call decompose()
on those divs.
例如,如果您要删除所有类为sidebar
的div,则可以使用
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()
如果您要删除具有特定id
的div,例如说main-content
,则可以使用
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()
这篇关于使用BeautifulSoup删除带有特定类的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!