VOOZH about

URL: https://www.geeksforgeeks.org/python/beautifulsoup-nextsibling/

⇱ Beautifulsoup - nextSibling - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Beautifulsoup - nextSibling

Last Updated : 16 Mar, 2021

The nextSibling property is used to return the next node of the specified node as Node object or null if the specified node is the last one in the list. It is a read-only property. In this article, we will find the next sibling(s) of a given tag that satisfies the given criteria and appears after this tag in the document.

Examples:

HTML_DOC :

 """

             <html>

              <head>

                  <title> Find Next Siblings </title>

              </head>

              <body>

                   <p class = "languages">1957: FORTRAN</p>

                   <p class = "languages">1972: C</p>

                   <p class = "languages">1983: C++</p>

                   <p class = "languages">1991: Python</p>

                   <p class = "languages">1993: Ruby</p>

                   <p class = "languages">1995: Java</p>

                   <p class = "languages">1995: PHP</p>

                   <p class = "languages">1995: JavaScript</p>

              </body>

            </html>

"""

element : <p class = "languages">1957: FORTRAN</p>

Output : 

                    <p class = "languages">1972: C</p>

                   <p class = "languages">1983: C++</p>

                   <p class = "languages">1991: Python</p>

                   <p class = "languages">1993: Ruby</p>

                   <p class = "languages">1995: Java</p>

                   <p class = "languages">1995: PHP</p>

                   <p class = "languages">1995: JavaScript</p>

Required Modules:

  • BeautifulSoup (bs4): It is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. Run the following command in the terminal to install this library-
pip install bs4
or
pip install beautifulsoup4

Finding Next Siblings:

find_next_siblings() function is used to find all the next siblings of a tag / element.

It returns all the next siblings that match.

Find Next Sibling:

find_next_sibling() function is used to find the succeeding sibling of a tag/element.

It only returns the first match next to the tag/element.

Example 1: Finding all the next siblings of a tag/element

Output:

👁 Image

Example 2: Finding the next sibling of a tag/element

Output:

👁 Image

Example 3: Finding the next sibling of Parent Tag (In the case of nested structure)

Output:

👁 Image

Example 4: Finding a specified number of next siblings.

For example, finding only the next 3 siblings of an element.
This can be done by using the limit argument

Output:

👁 Image
Comment
Article Tags: