Home > Software engineering >  Try except till element is visible within the HTML DOM using Selenium Python
Try except till element is visible within the HTML DOM using Selenium Python

Time:04-18

I am using selenium in python and here's a line that waits 20 seconds but sometimes still gives error as follows:

eleName = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='AutoNumber1']/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr/td/form/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr/td[1]/table/tbody/tr[3]/td/table/tbody/tr/td[2]/p/font/b")))

How can I use try except and after except statement say goto the same line to try again??

CodePudding user response:

To try the same line of code untill the operation is successfull you can wrapup the line of code within a try-break-except-continue{} block as follows:

while True:
    try:
        eleName = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='AutoNumber1']/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr/td/form/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr/td[1]/table/tbody/tr[3]/td/table/tbody/tr/td[2]/p/font/b")))
        break
    except TimeoutException:
        continue
# other lines of code

This block of code will continue to execute the line within try block in a loop, till the visibility of the WebElement eleName. Once the WebElement is found, the execution will break out of the loop.

  • Related