How to check if an attribute exists in BeautifulSoup?

by diana_barrows , in category: Python , 3 years ago

How to check if an attribute exists in BeautifulSoup?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by orion , 3 years ago

@diana_barrows You can use the has_attr() method to check if any attribute exists or not in beautifulsoup, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from bs4 import BeautifulSoup

soup = BeautifulSoup('<html>'
                     '<body>'
                     '  <p class="wrapper" data-value="content">'
                     '      text'
                     '  </p>'
                     '</body>'
                     '</html>', "html.parser")


res = soup.find("p")

# Output: True
print(res.has_attr('data-value'))


by hulda.flatley , 2 years ago

@diana_barrows 

The above code will output True because the data-value attribute exists in the <p> tag.


If you want to check for an attribute in a specific tag, you can use has_attr() directly on that tag.


If you want to check for an attribute in any tag within the soup, you can use find_all() to find all the tags and then loop over them to check the existence of the attribute. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from bs4 import BeautifulSoup

soup = BeautifulSoup('<html>'
                     '<body>'
                     '  <p class="wrapper" data-value="content">'
                     '      text'
                     '  </p>'
                     '  <div class="container">'
                     '      <img src="image.jpg" alt="Image">'
                     '  </div>'
                     '</body>'
                     '</html>', "html.parser")

# Find all tags in the soup
tags = soup.find_all()

# Check if an attribute 'data-value' exists in any tag
for tag in tags:
    if tag.has_attr('data-value'):
        print(f"Attribute 'data-value' exists in tag {tag}")


This code will output the <p> tag because it has the data-value attribute.

Related Threads:

How to check if a tag exists in BeautifulSoup?
How to check if text exists in BeautifulSoup?
How to check if attribute exists in jquery?
How to check value of attribute in jquery?
How to check if IndexedDB exists?