Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
BeautifulSoup - Modifying the tree
Next article icon

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> 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 Soupfrombs4importBeautifulSoup# Initialize the object with a HTML pagesoup=BeautifulSoup('''    <html>        <h2 class="hello"> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''',"lxml")# Get the whole h2 tagtag=soup.h2# Get the attributeattribute=tag.attrs# Print the outputprint(attribute)

Output: 

{'class': ['hello']}

Example 2: Program to extract the attributes using dictionary approach.
 

Python3
# Import Beautiful Soupfrombs4importBeautifulSoup# Initialize the object with a HTML pagesoup=BeautifulSoup('''    <html>        <h2 class="hello"> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''',"lxml")# Get the whole h2 tagtag=soup.h2# Get the attributeattribute=tag['class']# Print the outputprint(attribute)

Output: 

['hello']


Example 3: Program to extract the multiple attribute values using dictionary approach.

Python3
# Import Beautiful Soupfrombs4importBeautifulSoup# Initialize the object with a HTML pagesoup=BeautifulSoup('''    <html>        <h2 class="first second third"> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''',"lxml")# Get the whole h2 tagtag=soup.h2# Get the attributeattribute=tag['class']# Print the outputprint(attribute)

Output: 

['first', 'second', 'third']

Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp