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

OpenQA.Selenium.StaleElementReferenceException在try/catch块中仍触发调试中断(Selenium/C#/VS)

问题原因

Visual Studio调试器默认会对所有抛出的CLR异常触发中断,哪怕该异常后续会被代码中的catch块捕获。你的StaleElementReferenceException是在WebDriverWait.Until的委托逻辑内部抛出的,调试器会优先于你的catch块检测到这个异常并中断执行,导致你看到“异常未处理”的提示,但实际上代码的捕获逻辑是有效的,继续运行就会进入catch块处理。

解决方法

方法1:调整Visual Studio调试器的异常设置

  • 打开菜单栏的「调试」→「Windows」→「异常设置」
  • 在弹出的窗口中展开「Common Language Runtime Exceptions」,找到OpenQA.Selenium.StaleElementReferenceException
  • 取消勾选该异常的「抛出」(Thrown)选项,这样调试器只会在该异常未被捕获时才会中断,不会再干扰已被处理的异常。

方法2:优化代码逻辑(更健壮,减少异常触发)

当前代码在Until委托中直接查找元素并获取属性,一旦页面刷新,之前找到的元素就会失效抛出异常。可以修改等待逻辑,让Until每次都重新查找元素,避免 stale 问题:

int attempts = 0;
while (attempts < 2)
{
    try
    {
        wait = new WebDriverWait(edgeDriver, TimeSpan.FromSeconds(30));
        // 调整等待逻辑:每次重新查找元素,再检查内容
        var incidentElement = wait.Until(d => 
        {
            var elem = d.FindElement(By.Id("lblFormatedIncidentID"));
            return !string.IsNullOrEmpty(elem.GetAttribute("innerText")) ? elem : null;
        });
        incidentId = incidentElement.GetAttribute("innerText");
        break;
    }
    catch (StaleElementReferenceException)
    {
        Debug.Print("Failed to acquire Incident ID - Stale element error. Retrying...");
        attempts++;
        if (attempts == 2)
        {
            throw;
        }
    }
}

这种写法让WebDriverWait在每次轮询时都重新定位元素,从根源上减少StaleElementReferenceException的触发几率,同时也能复用找到的元素,避免重复查找。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:42:12