Search code examples
pythonseleniumif-statementselenium-webdrivertry-except

How to click on an element or the other using if-else logic using Selenium and Python for automated bot


I'm automating a bot to book a certain time (preferred time and second preferred time). I need help to use if else statement to allow the browser to search for the preferred time and if not present to search for the second preferred time.

Below is my code:

preferred_time=driver.find_element(By.XPATH,'//div[@class="booking-start-time-label"][contains(., "12:33pm")]')
preferred_time.click()
second_preferd_time= driver.find_element(By.XPATH,'//div[@class="booking-start-time-label"][contains(., "1:33pm")]')
second_preferd_time.click()

Solution

  • An ideal approach will be to try to click on the initial desired element inducing WebDriverWait for element_to_be_clickable() and incase it fails catch the TimeoutException and attempt to click on the second desired element as follows:

    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//div[@class="booking-start-time-label"][contains(., "12:33pm")]'))).click()
    except TimeoutException:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//div[@class="booking-start-time-label"][contains(., "1:33pm")]'))).click()
    

    Note: You have to add the following imports :

    from selenium.common.exceptions import TimeoutException
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC