PascalVKooten
PascalVKooten

Reputation: 21453

Find attribute name by value in BeautifulSoup (not reverse)

I'd like to automatically find the attribute name when knowing a unique value I'd be searching for in BeautifulSoup.

E.g.

>>> soup = '<div class="bla">123</div>'

"Knowing" 123, how would we get the output "bla"?

the opposite would simply be:

>>> soup.find("bla")
123

to get the value of the attribute "bla", but that's not what I'm looking for.

Upvotes: 1

Views: 322

Answers (1)

Celeo
Celeo

Reputation: 5682

From this section of the documentation:

for e in soup.find_all(text='123'):
    print(e.parent['class'])

We find all elements with the text of 123, and get the parent's CSS class.

Upvotes: 3

Related Questions