使用BeautifulSoup删除带有特定类的div [英] Deleting a div with a particlular class using BeautifulSoup

查看:640
本文介绍了使用BeautifulSoup删除带有特定类的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 divs 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆