Home > Software engineering >  Condition if element exist still continues even if the element is not existing in Selenium Python
Condition if element exist still continues even if the element is not existing in Selenium Python

Time:12-20

I have this code that if the element exists, it will print the innerHTML value:

def display_hotel(self):
    for hotel in self.hotel_data:
        if hotel.find_element(By.CSS_SELECTOR, 'span[]'):
            hotel_original_price = hotel.find_element(By.CSS_SELECTOR, 'span[]')
            hotel_original_price = hotel_original_price.get_attribute('innerHTML').strip().replace(' ', '')

            print(f"Original:\t\t\t{hotel_original_price}")

When I proceed and run the program, I get an error of

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"span[]"}

I was hoping that if the element span[] does not exist, it should just skip all together, why is it still trying to continue to do the code even under an if block? Am I missing anything here?

CodePudding user response:

In case the element is missing selenium driver throws an exception.
In order to make your code working you should use find_elements method.
It returns a list of elements matching the passed locator.
So, in case there are matches the list will contain web elements while in case there will be no matches it will return an empty list while python see non-empty list as a Boolean True and empty list is a Boolean False.
So your code could be as following:

def display_hotel(self):
    for hotel in self.hotel_data:
        if hotel.find_elements(By.CSS_SELECTOR, 'span[]'):
            hotel_original_price = hotel.find_element(By.CSS_SELECTOR, 'span[]')
            hotel_original_price = hotel_original_price.get_attribute('innerHTML').strip().replace(' ', '')

            print(f"Original:\t\t\t{hotel_original_price}")
  • Related