1

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?

Prophet
  • 32,350
  • 22
  • 54
  • 79
KiritoLyn
  • 626
  • 1
  • 10
  • 26

1 Answers1

1

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}")
Prophet
  • 32,350
  • 22
  • 54
  • 79
  • This works. Just a follow up question, when I use find_elements, it seems to search the entire element / document (not exactly sure) before it skips the non exiting element in the loop – KiritoLyn Dec 12 '21 at 16:13
  • I'm not sure I understand your question, I'm sorry – Prophet Dec 12 '21 at 16:16
  • let me rephrase, I mean it takes quite some time before it skips the loop, for example, if the element `span[class="_a11e76d75 _6b0bd403c"]` is not existing it'll take some few more seconds before proceeding to go through the next loop iteration. But if `span[class="_a11e76d75 _6b0bd403c"]` exists, it is fast (instant) to proceed to go to the next loop iteration. – KiritoLyn Dec 12 '21 at 22:48
  • Have you defined the `driver.implicitly_wait()` in your code? – Prophet Dec 13 '21 at 07:39