尝试使用 Selenium Python 直到元素在 HTML DOM 中可见

Try except till element is visible within the HTML DOM using Selenium Python

我在 python 中使用 selenium,这里有一行等待 20 秒但有时仍然会报错如下:

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")))

如何使用 try except 和 after except 语句说转到同一行再试一次?

要尝试相同的代码行直到操作成功,您可以将代码行包装在 try-break-except-continue{} 块中,如下所示:

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

此代码块将继续循环执行 try 块内的行,直到 WebElement eleName[= 可见21=]。一旦找到 WebElement,执行就会跳出循环。