Special functions to modify content
Apart from the methods we saw before, Beautiful Soup has the following other methods for modifying the content:
The
insert_after()
andinsert_before()
methods:As the name implies, these methods are used to insert a tag or string after or before another tag or string. The only parameter accepted by this method is the
NavigavleString
orTag
object.For example, we can add another
div
tag withclass=ecosystem
to the ecological pyramid example usinginsert_after()
. To use this, we need to first find thediv
tag withclass=number
within the first producerli
; this is shown as follows:soup = BeautifulSoup(html_markup,"lxml") div_number = soup.find("div",class_="number") div_ecosystem = soup.new_tag("div") div_ecosystem['class'] = "ecosystem" div_ecosystem.append("soil") div_number.insert_after(div_ecosystem) print(soup.prettify()) #output <html> <body> <div class="ecopyramid"> <ul id="producers"> <li class="producerlist...