Get tag name using Beautifulsoup in Python
tag.nameParameters: This function doesn't accept any parameter. Implementation: Example 1: Program to extract name of a XML tag.
# Import module
from bs4 import BeautifulSoup
# Initialize the object with a XML
soup = BeautifulSoup('''
<root>
<name_of_tag>the first strong tag</name_of_tag>
</root>
''', "lxml")
# Get the tag
tag = soup.name_of_tag
# Get the tag name
name = tag.name
# Print the output
print(name)
Output:
name_of_tag
Example 2: Program that explains the above functionality for a HTML tag.
# Import module
from bs4 import BeautifulSoup
# Initialize the object with a HTML page
soup = BeautifulSoup('''
<html>
<h2> Heading 1 </h2>
<h1> Heading 2 </h1>
</html>
''', "lxml")
# Get the whole h2 tag
tag = soup.h2
# Get the name of the tag
name = tag.name
# Print the output
print(name)
h2