Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - bs4, check if class has a value

So I have been playing around with bs4 abit and I found an issue that I cant managed to pass. What I want to do is that if there is a value in a class then we pass and if there is no value in class then we continue.

Situation one:

<option class="disabled RevealButton" value="1_120">
                            Overflow                        </option>


<option class="disabled RevealButton" value="1_121">
                            Stack                       </option>


<option class="disabled RevealButton" value="1_122">
                            !!!                        </option>

Situation 2

<option class="" value="1_120">
                            Overflow                        </option>


<option class="" value="1_121">
                            Stack                       </option>


<option class="" value="1_122">
                            !!!                        </option>

What I have done right now is:

try:
    select_tags = bs4.find('select', {'autocomplete': 'off'})
except Exception:
    select_tags = []

for select_tag select_tags:

    print(select_tag)

and what it does right now is that its printing either the first situation or second.

What I want for output is following:

if class contains disabled RevealButton then we just pass and continue the loop.

if class DOESN'T contains 'disabled RevealButton' then we print out select_tag

I have no clue what I can do to be able to solve my problem!

like image 854
Hellosiroverthere Avatar asked Dec 08 '25 06:12

Hellosiroverthere


1 Answers

To check if an element has disabled and RevealButton classes, you could use the dictionary-like interface of BeautifulSoup elements (Tag instances):

"disabled" in element["class"] and "RevealButton" in element["class"]

Note: you need to apply this on the option element.

Note that class is a special multi-valued attribute and its value is a list.


Another option (no pun intended) would be to look for option element with both classes:

for select_tag in select_tags:
    if select_tag.select("option.disabled.RevealButton"):
        continue

    print(select_tag)

Here, option.disabled.RevealButton is a CSS selector that would match option elements having both disabled and RevealButton classes.

like image 163
alecxe Avatar answered Dec 09 '25 19:12

alecxe