Home > Back-end >  Find element with Selenium
Find element with Selenium

Time:11-05

I need to find on Amazon page, like this. If the class exist, i need to set variable x == 0, if it doesn't exist, i need to set variable x == 1.

I tried this code, but it doesn't work. How can i check this?

try:
    couponBadge = driver.find_elements_by_class_name("a-icon a-icon-addon couponBadge")
    if couponBadge != None:
        x == 0
    else:
        x == 1
except AttributeError:
    print("error")
    

CodePudding user response:

You need to use a single equals sign, not two, to assign to a variable.

e.g. x = 1

It also looks like Selenium's get_elements_by_class_name function only supports inputting a single class name, not multiple as is shown in your example, so you might want to look into driver.find_element_by_css_selector().

e.g. driver.find_element_by_css_selector('.a-icon.a-icon-addon.couponBadge')

CodePudding user response:

Please try this:

couponBadge = driver.find_elements_by_class_name("a-icon a-icon-addon couponBadge")
if couponBadge:
    x = 0
else:
    x = 1    

driver.find_elements_by_class_name returns a list.
In case there are elements matching this locator the list will be non-empty, so it will be interpreted as a Boolean True. Otherwise it will be interpreted as False.
Also to assign a value to variable you should use a single =, not ==.
== is used for comparison.
Also, as mentioned by CrunchyBox you should rather use find_element_by_css_selector, not get_elements_by_class_name.

  • Related