Skip to content
Related Articles

Related Articles

Find the tag with a given attribute value in an HTML document using BeautifulSoup
  • Last Updated : 26 Mar, 2021

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :