Last modified: Jun 07, 2023 By Alexander Williams
BeautifulSoup: Get and Check Type Of Element
In this tutorial, we'll learn how to get and check the element type in BeautifulSoup.
Get the type of element
To get the type of an element using Beautiful Soup, you can follow this syntax:
type(element)
Let's see an example:
from bs4 import BeautifulSoup
# html source
html = """
<div>
<h1 class="el">This is H1</h1>
<h2 class="el">This is H2</h2>
<h3 class="el">This is H3</h3>
<div>
"""
# BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
# Find all with "el" class
els = soup.find_all(class_="el")
# Print Element type
for el in els:
print(type(el))
This code:
- Finds all elements with the class "el" by using
soup.find_all(class_="el")
. - Prints the type of each element using
print(type(el))
.
Here is the output:
<class 'bs4.element.Tag'>
<class 'bs4.element.Tag'>
<class 'bs4.element.Tag'>
So, when you see <class 'bs4.element.Tag'>
as the output of type(element)
, it confirms that the element is a Tag
object from Beautiful Soup, which you can further interact with using the available methods and attributes provided by Beautiful Soup.
Check the type of element
To check the type of element in Beautiful Soup, you can utilize the isinstance()
function in combination with the Tag
class provided by Beautiful Soup. Here's the syntax:
if isinstance(element, Tag):
print("Element is a Tag.")
else:
print("Element is not a Tag.")
the isinstance() returns True if
the element is a Tag
object and False
otherwise.
Let's see an example:
from bs4 import BeautifulSoup
from bs4.element import Tag
# HTML source
html = """
<div>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
</div>
"""
# BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
# Find the first <h1> element
element = soup.find('h1')
# Check the type of element
if isinstance(element, Tag):
print("Element is a Tag.")
else:
print("Element is not a Tag.")
Output:
Element is a Tag.
In this example, the code:
- Finds for the first
<h1>
element usingsoup.find('h1')
. - checks the type of the element using
isinstance(element, Tag)
.
Since the element is indeed a Tag
object, it prints "Element is a Tag."
Conclusion
In conclusion, By using the type()
function, you can determine the of an element, which is typically <class 'bs4.element.Tag'>
. And, by using isinstance()
function in combination with the Tag class you can check if an element belongs to the Tag
class.