How to find an element having an attribute of unknown value using BeautifulSoup?

Viewed 271

This is how it is done when attribute value we are looking for is known:

from bs4 import BeautifulStoneSoup
soup = BeautifulStoneSoup(html, 'html.parser')
found_elems = soup.find_all(attrs={"myattribute" : "myknownvalue"})

How do I find all elements with "myattribute" attribute, not knowing it's value?

2 Answers

If you don't know value of attribute, set it to True:

from bs4 import BeautifulStoneSoup
soup = BeautifulStoneSoup(html, 'html.parser')
found_elems = soup.find_all(attrs={"myattribute": True})

Another way is to use CSS selector:

found_elems = soup.select('[myattribute]')

More on CSS selectors here.

Related