Home > Enterprise >  How to loop code until it works in Python?
How to loop code until it works in Python?

Time:12-25

I have a long code, here is a small excerpt from it. You constantly need to find elements, insert data and click buttons. Sometimes something fails to load and errors pop up. Is it possible to have Python try these commands until it succeeds? I can't use

time.sleep() 

with a long delay as it will greatly increase the execution time and even that doesn't always help(

start = driver.find_element(By.CSS_SELECTOR, "SELECTOR")
start.click()
time.sleep(1)

start2 = driver.find_element(By.CSS_SELECTOR, "SELECTOR")
start2.click()
time.sleep(1)

CodePudding user response:

If you use a method that waits for an element to be clickable first, then you can set a default timeout, and then use that, as shown below with this partial code example that uses WebDriverWait:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


def wait_for_element_clickable(
    driver, selector, by="css selector", timeout=10
):
    try:
        return WebDriverWait(driver, timeout).until(
            EC.element_to_be_clickable((by, selector))
        )
    except Exception:
        raise Exception(
            "Element {%s} was not visible/clickable after %s seconds!"
            % (selector, timeout)
        )

# ...

element = wait_for_element_clickable(driver, "button#id")
element.click()
  • Related