首页 > 解决方案 > Selenium C# 请尝试/获取帮助

问题描述

我正在尝试在 Selenium C# 中编写一个 try/catch,如果 Web 元素不存在,则捕获 NoSuchElementException,如果元素存在,则抛出自定义异常。编码非常绿色,因此将不胜感激所有帮助。谢谢!

try
        {
          IWebElement spIcon = driver.FindElement(By.CssSelector("#gridview-1080-record-2658335 > td.x-grid-cell.x-grid-td.x-grid-cell-headerId-propertiesColInv.wrappable.icon-spacer.x-unselectable.wrappable.icon-spacer > div > i"));
        }
        catch (NoSuchElementException spIcoNotDisplayed)
        {
            //if spIcon is NOT present; 
            //then continue;
            //else throw custom exception 
        }

标签: c#seleniumautomated-tests

解决方案


var elementPresent = true;
try {
    IWebElement spIcon = driver.FindElement(By.CssSelector("#gridview-1080-record-2658335 > td.x-grid-cell.x-grid-td.x-grid-cell-headerId-propertiesColInv.wrappable.icon-spacer.x-unselectable.wrappable.icon-spacer > div > i"));
}
catch (NoSuchElementException spIconNotDisplayed) {
    elementPresent = false;
}

if (elementPresent) {
    throw new ElementPresentException("The spIcon was found");
}

推荐阅读