Home:ALL Converter>Selenium - How to look for one element ID and if it doesn't exist look for the next?

Selenium - How to look for one element ID and if it doesn't exist look for the next?

Ask Time:2021-09-22T05:44:37         Author:Dilshan

Json Formatter

I have a small selenium script, that goes to a website and checks some stuff and performs some steps. The issue I am having is. The "s2id_ddlHotels" ID sometimes changes. The bot will find "s2id_ddlHotels" and finish the steps. But the next run it will load this element "s2id_ddlHotelsWithDate". It's only between these two elements so far I've seen. How can I handle this? Sort of tells the python code to look for "s2id_ddlHotels" first, if found do the other steps. and if that cannot be found, look for "s2id_ddlHotelsWithDate" and do the steps? I believe I have to use an IF statement here but I'm unsure how to properly implement it.

My current code:

try:
        time.sleep(5)
        driver.find_element_by_id("s2id_ddlHotels").click() #issue here
        time.sleep(2)
        driver.find_element_by_id('s2id_autogen1_search').send_keys(hotelName)
        time.sleep(2)
        driver.find_element_by_id('s2id_autogen1_search').send_keys(Keys.RETURN)
        time.sleep(2)
        driver.find_element_by_name("fileRoomIncomeName").send_keys(fileName)
        time.sleep(2)
        element = driver.find_element_by_class_name("fileupload-preview")
        driver.execute_script(f"arguments[0].innerText = '{fileName}'", element)
    except Exception as e:
        pass
        #print(e)

Author:Dilshan,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275875/selenium-how-to-look-for-one-element-id-and-if-it-doesnt-exist-look-for-the-n
yy