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

Selenium使用WebDriverWait点击元素触发ElementIntercepted异常如何解决

问题原因与解决方案

核心错误点

  • 输入框定位规则完全错误:你代码中查找月、日、年输入框时使用的By.Name("01")、By.Name("1993")不符合实际HTML结构,三个激活态输入框的真实name属性为dob-month、dob-day、dob-year,错误定位会直接导致操作失败。
  • 点击操作存在时序缺陷:仅判断非激活输入框可见就执行点击,此时页面可能存在未消失的遮罩、未完成的加载动画、DOM交互状态未就绪,就会触发ElementIntercepted异常。

修复代码

ChromeOptions options = new ChromeOptions();
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
options.AddArgument("--user-agent=Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25");
IWebDriver driver = new ChromeDriver(driverService, options);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
driver.Manage().Cookies.DeleteAllCookies();
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);

System.Drawing.Size size = new System.Drawing.Size(200, 400);
driver.Manage().Window.Size = size;

driver.Navigate().GoToUrl("https://account.battle.net/creation/flow/creation-full");

// 定位非激活日期输入框,先等可点击再滚动到视口中心
var inactiveDob = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("dob-plain")));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView({block: 'center'});", inactiveDob);

// 重试点击机制,最多重试3次,捕获拦截异常后重试
int retryCount = 3;
while (retryCount > 0)
{
    try
    {
        // 仍有拦截可以替换为JS点击:((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", inactiveDob);
        inactiveDob.Click();
        break;
    }
    catch (ElementInterceptedException)
    {
        retryCount--;
        Thread.Sleep(500);
        if (retryCount == 0) throw;
    }
}

// 等待激活态日期组件完全显示(等待phantom隐藏类移除)
wait.Until(d => !d.FindElement(By.Id("dob-field-active")).GetAttribute("class").Contains("phantom"));

// 输入对应日期,使用正确的name属性定位
wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("dob-month"))).SendKeys(month.ToString());
wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("dob-day"))).SendKeys(day.ToString());
wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("dob-year"))).SendKeys(year.ToString());

补充说明

之前使用JavaScript Executor无效大概率是执行时机不对、或者定位的元素错误,上述修正时序逻辑后使用JS点击可以解决绝大多数元素拦截问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:45:02