Extracting an attribute value with beautifulsoup in Python Read Courses Practice Improve Improve Improve Like Article Like Save Article Save Report issue Report Prerequisite: Beautifulsoup Installation Attributes are 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. A tag may have any number of attributes. For example, the tag <b class=”active”> has an attribute âclassâ whose value is âactiveâ. We can access a tagâs attributes by treating it like a dictionary. Syntax: tag.attrs Implementation:Example 1: Program to extract the attributes using attrs approach. Python3 # Import Beautiful Soup from bs4 import BeautifulSoup # Initialize the object with a HTML page soup = BeautifulSoup(''' <html> <h2 class="hello"> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', "lxml") # Get the whole h2 tag tag = soup.h2 # Get the attribute attribute = tag.attrs # Print the output print(attribute) Output: {'class': ['hello']} Example 2: Program to extract the attributes using dictionary approach. Python3 # Import Beautiful Soup from bs4 import BeautifulSoup # Initialize the object with a HTML page soup = BeautifulSoup(''' <html> <h2 class="hello"> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', "lxml") # Get the whole h2 tag tag = soup.h2 # Get the attribute attribute = tag['class'] # Print the output print(attribute) Output: ['hello'] Example 3: Program to extract the multiple attribute values using dictionary approach. Python3 # Import Beautiful Soup from bs4 import BeautifulSoup # Initialize the object with a HTML page soup = BeautifulSoup(''' <html> <h2 class="first second third"> Heading 1 </h2> <h1> Heading 2 </h1> </html> ''', "lxml") # Get the whole h2 tag tag = soup.h2 # Get the attribute attribute = tag['class'] # Print the output print(attribute) Output: ['first', 'second', 'third'] Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve. Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore. Last Updated : 29 Dec, 2020 Like Article Save Article Previous Get tag name using Beautifulsoup in Python Next BeautifulSoup - Modifying the tree Share your thoughts in the comments Add Your Comment Please Login to comment...