Related Articles

Related Articles

Get tag name using Beautifulsoup in Python
  • Last Updated : 11 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

name_of_tag

Example 2: Program that explains the above functionality for a HTML tag.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

h2

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :