BeautifulSoup: .has_attr() with Examples

Syntax

has_attr('attribute')

Example

from bs4 import BeautifulSoup


# Html source
html_source = '''
<div>
<h1>home 1</h1>
<h2 id="home">home 2</h2>
</div>
'''

# Parsing
soup = BeautifulSoup(html_source, 'html.parser')

# Get h1 tag
h1 = soup.h1
# Get h2 tag
h2 = soup.h2

# Check if has attribute ID
check_h1 = h1.has_attr('id')
check_h2 = h2.has_attr('id')

# Print
print(check_h1)
print(check_h2)

Output:

False
True