Open In App

Find the tag with a given attribute value in an HTML document using BeautifulSoup

Last Updated : 26 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites: Beautifulsoup

In this article, we will discuss how beautifulsoup can be employed to find a tag with the given attribute value in an HTML document.

Approach:

  • Import module.
  • Scrap data from a webpage.
  • Parse the string scraped to HTML.
  • Use find() function to find the attribute and tag.
  • Print the result.

Syntax: find(attr_name=”value”)

Below are some implementations of the above approach:

Example 1: 

Python3




# importing module 
from bs4 import BeautifulSoup 
    
markup = '''<html><body><div id="container">Div Content</div></body></html>'''
soup = BeautifulSoup(markup, 'html.parser'
    
# finding the tag with the id attribute
div_bs4 = soup.find(id = "container"
    
print(div_bs4.name)


Output:

div

Example 2:

Python3




# importing module 
from bs4 import BeautifulSoup 
    
markup = '''<html><body><a href="https://www.geeksforgeeks.org/">Geeks for Geeks</a></body></html>'''
soup = BeautifulSoup(markup, 'html.parser'
    
# finding the tag with the href attribute
div_bs4 = soup.find(href = "https://www.geeksforgeeks.org/"
    
print(div_bs4.name)


Output:

a

Example 3:

Python3




# importing module 
from bs4 import BeautifulSoup 
    
markup = """<html><head><title>Welcome  to geeksforgeeks</title></head> 
<body> 
<p class="title"><b>Geeks</b></p>
    
<p class="gfg">geeksforgeeks a computer science portal for geeks 
</body> 
"""
soup = BeautifulSoup(markup, 'html.parser'
    
# finding the tag with the class attribute
div_bs4 = soup.find(class_ = "gfg"
    
print(div_bs4.name)


Output:

p


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads