Open In App

Get tag name using Beautifulsoup in Python

Last Updated : 11 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Beautifulsoup Installation

Name property is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Name object corresponds to the name of an XML or HTML tag in the original document.

Syntax:

tag.name

Parameters: This function doesn’t accept any parameter.

Implementation:
Example 1: Program to extract name of a XML tag.

Python3




# 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.

Python3




# 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)


Output:

h2


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

Similar Reads