pythonseleniumselenium-webdriverwebdriverwebdriverwait

How to use WebDriverWait in an if statement for multiple elements efficiently?


Assuming that I have 3 different scenarios in those different scenarios different elements are shown.

How can I use WebDriverWait for multiple elements and if one of those elements are found ignore the finding of other elements.

I had tried WebDriverWait to sleep for x number of seconds then do an if statement with driver.find_element_by_id and find if the elements are present but this is highly inefficient because the page can take longer/less to load, you can see what I tried in the following code:

WebDriverWait(driver, 30)
if len(driver.find_elements_by_id('something1')) > 0:
    *do something*
elif len(driver.find_element_by_id('something2')) > 0:
    *do something*
elif len(driver.find_element_by_id('something3')) > 0:
    *do something*

I also tried WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID, 'something'))) with a try and except but this is the most inefficient method as it because it takes much more longer longer.


Solution

  • In order to wait until one of three elements is presented you can use the following ExpectedConditions example since
    ExpectedConditions supports multiple arguments.
    So you can use something like the following:

    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "first_element_id, second_element_id, third_element_id"))
    

    Now, if you need to know what element is present and what not, the simplest way to do that is using the driver.find_elements

    is_first_element_present = driver.find_elements_by_id(first_element_id)
    is_second_element_present = driver.find_elements_by_id(second_element_id)
    is_third_element_present = driver.find_elements_by_id(third_element_id)
    

    Now, each of those elements is a list. In case the element is present, the list is not empty and in case the element is absent the list is empty. And since non-empty list is Boolean True in Python and empty list is False you can use it directly with if case:

    if(is_first_element_present):
       do_something
    elif(is_second_element_present):
       do_that
       -----
    etc