You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium中if elif else无法进入elif分支,报NoSuchElementException错误

问题产生原因

Selenium 自带的find_element系列定位方法的底层逻辑是:只要页面上找不到匹配的目标元素,就会直接抛出NoSuchElementException异常终止程序,不会返回布尔值触发分支跳转。
你现有代码的第一个判断直接调用driver.find_element_by_class_name('error-code').is_displayed(),当页面不存在error-code元素时,还没执行到is_displayed()的可见性判断,定位步骤就已经抛出异常,自然无法进入后续的elif、else分支。

修复方案

我们可以先封装一个通用的元素可见性判断方法,内部捕获元素不存在的异常,元素不存在/不可见时统一返回False,完全适配你的分支判断逻辑:

第一步:导入依赖

from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

第二步:封装通用判断方法

def is_element_displayed(driver, locate_by, locate_value):
    try:
        target = driver.find_element(locate_by, locate_value)
        return target.is_displayed()
    except NoSuchElementException:
        # 元素不存在直接返回False,触发下一个分支判断
        return False

第三步:修改原有业务逻辑代码

if is_element_displayed(driver, By.CLASS_NAME, 'error-code'):
    LoginError.show()
elif is_element_displayed(driver, By.XPATH, '//*[@id="sample-data-table"]/thead'):
    QuestionUnavailable.show()
else:
    if is_element_displayed(driver, By.XPATH, '//*[@id="radio1"]'):
        driver.find_element(By.XPATH, '//*[@id="radio1"]').click()
        driver.find_element(By.XPATH, '//*[@id="btn-savecheck"]').click()
        time.sleep(1)
        driver.find_element(By.XPATH, '//*[@id="btn-alert-ok"]').click()

旧版Selenium兼容说明

如果你使用的是Selenium 3及更早版本,不想替换find_element_by_xx的写法,也可以直接在每个判断分支里单独捕获异常,仅复用性更低:

# 仅示例第一个判断,剩余分支按相同逻辑修改即可
try:
    error_code_visible = driver.find_element_by_class_name('error-code').is_displayed()
except NoSuchElementException:
    error_code_visible = False

if error_code_visible:
    LoginError.show()
# 后续分支逻辑同上

内容的提问来源于stack exchange,提问作者Adam Khattab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:54:04