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 soup = BeautifulSoup(markup, 'html.parser' ) # finding the tag with the href attribute print (div_bs4.name) |
Output:
a
Example 3:
Python3
# importing module from bs4 import BeautifulSoup markup = """<html><head><title>Welcome to neveropen</title></head> <body> <p class="title"><b>Geeks</b></p> <p class="gfg">neveropen a computer science portal for Lazyroar </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