使用 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?
推荐答案
当然,你可以选择
、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屋!