Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - Deleting a div with a particlular class using BeautifulSoup

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

According to documentation we can use div.decompose().

But that would delete all the div. How can I delete a div with specific class?

question from:https://stackoverflow.com/questions/32063985/deleting-a-div-with-a-particlular-class-using-beautifulsoup

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...