Last modified: Nov 04, 2023 By Alexander Williams

Beautiful Soup find_previous() Method Examples

Example 1: Finding the Previous <p> Tag

    
from bs4 import BeautifulSoup

html = """
<p>First paragraph</p> <p>Second paragraph</p> <p>Third paragraph</p>
""" soup = BeautifulSoup(html, 'html.parser') target_tag = soup.find('p', text='Second paragraph') # Find the previous <p> tag previous_tag = target_tag.find_previous('p') print(previous_tag.text)

Output:

    
First paragraph
    

Example 2: Finding the Previous <div> Tag with a Specific Class

from bs4 import BeautifulSoup

html = """
<div class="container">
    <p>Inside the container</p>
</div>

<div class="content">
    <p>Inside the content</p>
</div>
"""

soup = BeautifulSoup(html, 'html.parser')
target_tag = soup.find('div', class_='content')

# Find the previous <div> tag with class "container"
previous_div = target_tag.find_previous('div', class_='container')
print(previous_div['class'])

Output:


['container']

Example 3: Finding the Previous <h2> Tag

    
from bs4 import BeautifulSoup

html = """
<h1>Main Title</h1>
<h2>Subheading 1</h2>
<p>Some text</p>
<h2>Subheading 2</h2>
<p>More text</p>
"""

soup = BeautifulSoup(html, 'html.parser')
target_tag = soup.find('h2', text='Subheading 2')

# Find the previous <h2> tag
previous_h2 = target_tag.find_previous('h2')
print(previous_h2.text)
    

Output:

    
Subheading 1
    

Example 4: Finding the Previous <a> Tag with Specific Attributes

    
from bs4 import BeautifulSoup

html = """
<a href="https://example.com">Visit Example</a>
<p>Some text</p>
<a href="https://example.org" class="external">Visit Example.org</a>
<p>More text</p>
"""

soup = BeautifulSoup(html, 'html.parser')
target_tag = soup.find('a', class_='external')

# Find the previous <a> tag with a specific class
previous_a = target_tag.find_previous('a', href="https://example.com")
print(previous_a['href'])
    

Output:

    
https://example.com
    

Example 5: Finding the Previous <ul> Tag

    
from bs4 import BeautifulSoup

html = """
<div>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
</div>
<p>Some text</p>
<ul>
    <li>Item A</li>
    <li>Item B</li>
</ul>
"""

soup = BeautifulSoup(html, 'html.parser')
target_tag = soup.find('ul')

# Find the previous <ul> tag
previous_ul = target_tag.find_previous('ul')
print(previous_ul)
    

Output:

    
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
</ul>