如何在Python Selenium中用try-except从多元素中找到有效元素并返回
问题解决:Selenium依次检查元素直到找到有效项并返回
原代码的核心问题
self.findelement()找到元素时返回WebElement对象,不是布尔值,elem == True的判断逻辑完全错误。- 一旦某个
self.findelement()找不到元素,会直接抛出异常进入except块,无法继续检查后续元素,根本实现不了“依次检查直到找到”的需求。
优化后的代码
把定位器和对应状态标识做成映射列表,循环遍历尝试查找,找到有效元素后立即终止并返回:
def status(self): # 定义状态定位器与对应标识的映射 status_list = [ (Objects.status_1, "A"), (Objects.status_2, "B"), (Objects.status_3, "C"), (Objects.status_4, "D"), (Objects.status_5, "E") ] try: for locator, status_tag in status_list: # 用find_elements避免找不到元素时抛异常 elem = self.driver.find_elements(*locator) if elem: result = f"The status is : {status_tag}" print(result) return result # 遍历完所有定位器都没找到的情况 raise AssertionError("Failed to fetch the status") except Exception as e: print(e) raise AssertionError("Failed to fetch the status")
关键说明
- 映射列表的写法让后续新增/修改状态更方便,不用改循环逻辑。
- 使用
find_elements()代替find_element():找不到元素时返回空列表,不会触发异常,能继续检查下一个定位器。 - 找到有效元素(
elem不为空)时,立即打印结果并返回,终止循环。
预期输出
当匹配到Objects.status_4对应的元素时,输出:
The status is : D
内容的提问来源于stack exchange,提问作者Abhi
相关产品推荐
相关产品推荐

