python - 尝试使用 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”(预期),截取屏幕截图(预期)并且脚本停止(预期)。
但是,我觉得我错过了一些东西。
有没有更好的方法来检查错误按钮的存在?
解决方案
您可以简单地使用find_elements_by_id
并获取计数。
errEleCount = len(driver.find_elements_by_id("errorShowMore"))
if errEleCount>0:
# implement the logic here.
推荐阅读
- kubernetes - 企业代理背后的 kubeadm init
- python - Python 中的 Google Analytics(分析)页面路径市场篮分析
- codeigniter - 已发送但未收到的电子邮件
- pandas - 如果是数字列,则减去 2 个数据框;对于文本使用最新的数据框
- xslt - XSLT3 Streaming 用于附加节点的整数位置
- python - 如何在 QTreeView 上显示文件夹内容以及 PyQt5 中的可见文件夹?
- entity-framework-core - 使用自定义集合类型作为支持字段
- server - 服务器场马尔可夫链队列的容量配置
- r - 如何格式化数据以自动化表格制作?
- python - 在 RdBu 颜色图的情况下,为什么 cm.get_cmap 没有通过 (0,1) 给出深红色和蓝色?