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

Selenium Webdriver C#调用isDisplayed、Displayed校验元素显示状态报错求助

Selenium C# 元素可见性校验问题解决方案

错误根因

  • CS1061报错原因:isDisplayed()是Java版本Selenium的API,C#版本Selenium的IWebElement接口没有该方法,二者API设计存在差异。
  • CS1955报错原因:C#版本Selenium中判断元素可见性的Displayed是布尔属性,不是方法,调用时不能加括号,加括号会被识别为方法调用逻辑,因此触发报错。

正确实现方式

基础写法

注意修正CSS选择器的多余空格,原写法.mat - select中间的空格会导致选择器匹配失效,需改为.mat-select:

// 直接访问Displayed属性获取可见性状态
Boolean Display = Driver.FindElement(By.CssSelector(".mat-select")).Displayed;

Driver.FindElement本身在找不到对应元素时会直接抛出NoSuchElementException异常,会自动终止测试,符合你“不存在则抛出错误终止测试”的需求。

优化写法(推荐)

直接调用FindElement如果元素还未渲染完成会直接报错,建议增加显式等待逻辑,提升用例稳定性:

// 先引入必要命名空间
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;

// 最多等待10秒,直到目标元素可见
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
IWebElement matSelectElement = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".mat-select")));
// 等待通过后直接使用matSelectElement执行后续操作即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:15:02