BeautifulSoup: .attrs example

Syntax

element.attrs

Example 1:

from bs4 import BeautifulSoup

# Html source
html = """
<div>
<h2 class="recent">Recent Posts:</h2>
</div>
"""

# Parse
soup = BeautifulSoup(html, 'html.parser')

# Get h2 tag
h2 = soup.h2

# Print h2 attribute
print(h2.attrs)

Output:

{'class': ['recent']}

Example 2:

from bs4 import BeautifulSoup

# Html source
html = """
<div>
<h2 class="recent" id="attribute">Recent Posts:</h2>
</div>
"""

# Parse
soup = BeautifulSoup(html, 'html.parser')

# Get h2 tag
h2 = soup.h2

# Print h2 attribute
print(h2.attrs)

Output:

{'class': ['recent'], 'id': 'attribute'}