Search code examples
python-3.xseleniumselenium-webdriverfindelement

Condition if element exist still continues even if the element is not existing in Selenium Python


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[class="_a11e76d75 _6b0bd403c"]'):
            hotel_original_price = hotel.find_element(By.CSS_SELECTOR, 'span[class="_a11e76d75 _6b0bd403c"]')
            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[class="_a11e76d75 _6b0bd403c"]"}

I was hoping that if the element span[class="_a11e76d75 _6b0bd403c"] 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?


Solution

  • 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[class="_a11e76d75 _6b0bd403c"]'):
                hotel_original_price = hotel.find_element(By.CSS_SELECTOR, 'span[class="_a11e76d75 _6b0bd403c"]')
                hotel_original_price = hotel_original_price.get_attribute('innerHTML').strip().replace(' ', '')
    
                print(f"Original:\t\t\t{hotel_original_price}")