Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Getting Started with Beautiful Soup

You're reading from   Getting Started with Beautiful Soup Learn how to extract information from websites using Beautiful Soup and the Python urllib2 module. This practical, hands-on guide covers everything you need to know to get a head start in website scraping.

Arrow left icon
Product type Paperback
Published in Jan 2014
Publisher Packt
ISBN-13 9781783289554
Length 130 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Vineeth G Nair Vineeth G Nair
Author Profile Icon Vineeth G Nair
Vineeth G Nair
Arrow right icon
View More author details
Toc

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() and insert_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 or Tag object.

    For example, we can add another div tag with class=ecosystem to the ecological pyramid example using insert_after(). To use this, we need to first find the div tag with class=number within the first producer li ; 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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime