Python Selenium with multiple

Viewed 29

I'm having trouble trying to make a script with 2 conditions and choosing the first condition that appears something like:

    try:
        element = WebDriverWait(driver, 800).until( 
           EC.presence_of_element_located((By.CLASS_NAME, value="class show"))  
        ).click()
        print ("1st element clicked")
        time.sleep (10)
        element = WebDriverWait(driver, 10).until_not(EC.title_contains(("how to get"))),

        or
        element = WebDriverWait(driver, 800).until_not( 
            EC.title_contains((word)) 
         )  
        print ("2st element clicked")
    except:
        pass
        print("skip to next step")

    print ("finish")

the script wait until 1st or 2nd condition appears first, if nothing appear until timeout, skip to next step.

1 Answers

Try this code which doesn't use WebDriverWait, instead it uses time.sleep() and try/except with NoSuchElementException

import time
from selenium.common.exceptions import NoSuchElementException

...import other libraries and start the driver...

seconds_to_wait = 20
start = time.time()

while (time.time() - start) < seconds_to_wait:
    
    try:
        element = ... # for example element = driver.find_element(By.CLASS_NAME, "class show")
        found = True
    except NoSuchElementException:
        found = False
    
    if found:
        element.click()
        print("1st element clicked")
        break
    
    try:
        element = ...
        found = True
    except NoSuchElementException:
        found = False
    
    if found:
        element.click()
        print("2nd element clicked")
        break

    time.sleep(1)

print("finish")
Related