首页 > 解决方案 > 尝试使用 except 语句来测试是否存在错误按钮,如果找到元素则抛出异常

问题描述

我编写了一个 Python / Selenium 脚本来自动化金融网站上的工作流程。

其中一项测试涉及检查其中一个屏幕上是否存在错误文本。

附加的是一个 Try / except 块,用于检查按钮的存在(id = errorShowMore)。如果显示按钮,我希望脚本失败并且我想截取页面的屏幕截图。

我编写了标识错误按钮的代码。然后,我将此代码放入 Try / except 块中。

但是,我对如何改进这个错误处理结构有疑问(如果可以改进的话)。

try:
    showMoreButton = driver.find_element_by_id("errorShowMore")
    assert showMoreButton.click() except AssertionError:
    screenshot_name = "FAIL" + "_" + test_case_ID + "_" + browser + "_" + env + "_" + time_stamp + ".png"
    saved_screenshot_location = str(screenshot_directory / screenshot_name)
    driver.get_screenshot_as_file(saved_screenshot_location)
    raise

当我运行代码并且存在错误时,我得到一个“AssertionError”(预期),截取屏幕截图(预期)并且脚本停止(预期)。

但是,我觉得我错过了一些东西。

有没有更好的方法来检查错误按钮的存在?

标签: pythonseleniumtry-catchassertionwebpage-screenshot

解决方案


您可以简单地使用find_elements_by_id并获取计数。

errEleCount = len(driver.find_elements_by_id("errorShowMore"))
if errEleCount>0:
  # implement the logic here.

推荐阅读