Beautiful Soup - Functions Reference

Beautiful Soup Useful Resources

Beautiful Soup - previous_sibling Property



Description

The HTML tags appearing at the same indentation level are called siblings. The previous_sibling property of the PageElement returns a previous tag (a tag appearing before the current tag) at the same level, or under the same parent. This property encapsulates the find_previous_sibling() method.

Syntax

element.previous_sibling

Return type

The previous_sibling property returns a PageElement, a Tag or a NavigableString object.

Example - Usage of previous_sibling property

In the following code, the HTML string consists of two adjacent tags inside a <p> tag. It shows the sibling tag for <b> tag appearing before it.

from bs4 import BeautifulSoup

soup = BeautifulSoup("<p><b>Hello</b><i>Python</i></p>", 'html.parser')
tag = soup.i
sibling = tag.previous_sibling
print (sibling)

Output

<b>Hello</b>

Example - Using previous_sibling property for input fields

We are using the index.html file for parsing. The page contains a HTML form with three input elements. Which element is a previous sibling of input element with its id attribute as age? The following code shows it −

from bs4 import BeautifulSoup

html = """
<html>
   <head>
      <title>TutorialsPoint</title>
   </head>
   <body>
      <form>
         <input type = 'text' id = 'nm' name = 'name'>
         <input type = 'text' id = 'age' name = 'age'>
         <input type = 'text' id = 'marks' name = 'marks'>
      </form>
   </body>
</html>
"""

soup = BeautifulSoup(html, 'html.parser')

tag = soup.find('input', {'id':'age'})
sib = tag.previous_sibling.previous_sibling
print (sib)

Output

<input id="nm" name="name" type="text"/>

Example - Finding a Previous Sibling for P tag

First we find the <p> tag containing the string 'Tutorial' and then finds a tag previous to it.

from bs4 import BeautifulSoup

html = '''
<p>Excellent</p><p>Python</p><p>Tutorial</p>
'''
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tag = soup.find('p', string='Tutorial')
print (tag.previous_sibling)

Output

<p>Python</p>
Advertisements