【问题标题】:Issue with python selenium using try except block with while loop to retry after failing [duplicate]python selenium的问题,使用try except块和while循环在失败后重试[重复]
【发布时间】:2019-12-02 15:54:21
【问题描述】:

我正在尝试使用 selenium webdriver 单击页面上的返回按钮。有时,可能会因为加载而第一次失败,所以我把代码放在了while try except block中,让它在失败后重试:

while True:
    try:
        driver.find_element_by_class_name("back_button")
        driver.click()
    except:
        time.sleep(1)
        print("Unable to go back")
        continue
    break

理想情况下,当 try 块中的部分成功执行时,代码应该继续前进,但我发现有时它仍然会尝试单击返回按钮,而它已经在上一页上。然后它会永远卡在 while 循环中,因为该页面上没有返回按钮。可能的原因是什么?

【问题讨论】:

  • except: 无一例外(例如except TimeoutException:)在 Selenium 和一般编程中都是非常危险的做法。你想在这里捕捉什么异常?如果您在 except 块中指定异常,您的代码中出了什么问题可能会变得更加清楚。如果不知道异常,也不知道您正在自动化的页面的上下文,也很难解决您的问题。
  • 我正在尝试在这里捕捉ElementNotInteractableException
  • 这是有道理的,如果页面没有完全加载完成,就会抛出该错误。如果抛出错误,我将为此问题添加额外的解决方法。

标签: python selenium exception


【解决方案1】:

如果您的代码由于加载而第一次失败,就像您在问题描述中所说的那样,将其包装在 try / except 中并用 while(true) 循环包围并不是处理此问题的好方法,因为您最终可能会遇到某些情况,使您陷入while(true) 循环。

最好在单击之前对要加载的元素调用WebDriverWait。用try / except 包裹东西真的应该是最后的手段。

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# need the above import statements

back_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "back_button")))

back_button.click()

# alternative -- if this code STILL throws ElementNotInteractable, try the below:
# driver.execute_script("arguments[0].click();", back_button)
# ^ this clicks with Javascript, which can work around ElementNotInteractable.

如果您真的想将其包装在 try / except 块中以检查 back_button 未在 10 秒内加载的情况,可以使用此:

from selenium.common.exceptions import TimeoutException
# import the exception you need to catch

try:
    back_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "back_button")))

    back_button.click()
except TimeoutException: # WebDriverWait throws TimeoutException if it fails
    print("back_button did not appear on page within 10 seconds.")

如果你的click() 真的只是因为加载问题而失败,上面的代码应该完全消除你对try / except 的需要。

另外值得一提的是,除了我对你的问题留下的评论之外——使用except: 毫无例外地捕捉是非常危险的做法,因为你真的不知道你的代码为什么会失败。将来使用except: 时,您应该真正寻找特定 异常,例如except TimeoutException:except NoSuchElementException:。这将使您免于日后的调试噩梦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2022-11-02
    相关资源
    最近更新 更多