Search code examples
pythonseleniumwebdriverwaitmultiple-conditions

Multiple conditions using python selenium webdriver wait-until


I almost sure that there are few simple solutions for that, but.. i'm clicking an element of web page and one of more than 2 different pages can appear after it. Than i need to click one of the specific elements for each kind of result pages.
If i had 2 variants i could use TRY and EXCEPT + WebDriverWait.until structures.

lesson = driver.find_element_by_xpath('//input[@class = "playButton"]')
lesson.click()
try:
    WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//div[@class = "cursor-hover"]')))
    start_b = driver.find_element_by_xpath('//div[@class = "cursor-hover"]')
    start_b.click()
except:
    WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.XPATH, '//div[@class = "cursor-hover2"]')))
    start_g = driver.find_element_by_xpath('//div[@class = "cursor-hover2"]')
    start_g.click()

This structure works perfect. If there is no first element - the second one is clicked. So what can i use to successfully identify the only element of 5 or more?


Solution

  • Probably having a list of possible xpaths and iterating through them would be the easiest solution.

    # possible xpaths depending on what page will be opened afterwards
    possible_xpaths = ['//div[@class = "cursor-hover1"]', '//*[@class="something else"]', ...]
    
    for xpath in possible_xpaths:
        try:
            WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, xpath)))
            element = driver.find_element_by_xpath(xpath)
            element.click()
            break # found the correct element
        except:
            pass # continue to try the next xpath