Home > OS >  How to Python code an if else condition at a webdriver wait until juncture
How to Python code an if else condition at a webdriver wait until juncture

Time:09-08

At the moment, I'm using a wait until pause in my selenium Python program:

    # wait until shipping estimate loaded
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#freightCalculatorForm > div > fieldset.col-xs-12.col-lg-6.col-md-6.text-center > div.freightCalcResult > div > p:nth-child(2)"))
    )

The problem is that if the wait until reaches the end of the allowed time, it will throw a timeout error and then stop my program. But I want my program to continue at that point according to an if/else directive:

In other words, I want:

If the wait until succeeds in detecting the element
    # return the element  
Else the wait until times out 
    # do something else instead, and continue with the rest of the program

How can I code this if/else in Python selenium with the above wait until?

CodePudding user response:

Instead of if-elif you can use try-except as following:

try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#freightCalculatorForm > div > fieldset.col-xs-12.col-lg-6.col-md-6.text-center > div.freightCalcResult > div > p:nth-child(2)")))
    # do what you need to do in case the element found
except:
    # do what you want to do in case no element found

CodePudding user response:

You can simply use try except pass statement

try:
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#freightCalculatorForm > div > fieldset.col-xs-12.col-lg-6.col-md-6.text-center > div.freightCalcResult > div > p:nth-child(2)")))
except:
    pass
  • Related