0

I am trying to get selenium set up to send out messages automatically and have not yet got around to check if the specific listing has already been sent a message. This causes selenium to give a NoSuchElementException because its looking for (By.XPATH, ('//span[contains(text(),"Message")]')) How can I have it skip these pages where the element doesn't exist?

message = driver.find_element(By.XPATH, ('//span[contains(text(),"Message")]'))
   
message.click()

Very small snippet that shows the code where the issue is.

Prophet
  • 32,350
  • 22
  • 54
  • 79
hmark
  • 1
  • 1

1 Answers1

0

Instead of find_element you should use find_elements here.
find_elements returns a list of found matches. So, in case of match (such element exists) it will return non-empty list. It will be interpreted by Python as Boolean True. Otherwise, in case of no matches found the returned list is empty, it is interpreted by Python as Boolean False.
To perform click you can get the first element in the returned list, as following:

message = driver.find_elements(By.XPATH, ('//span[contains(text(),"Message")]'))
if message:
    message[0].click()
Prophet
  • 32,350
  • 22
  • 54
  • 79