Tuesday, November 19, 2024
Google search engine
HomeLanguagesGet tag name using Beautifulsoup in Python

Get tag name using Beautifulsoup in Python

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

RELATED ARTICLES

Most Popular

Recent Comments