【问题标题】:Selenium C# try/catch assistance pleaseSelenium C# 请尝试/获取帮助
【发布时间】:2018-11-20 14:46:43
【问题描述】:

我正在尝试在 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 
        }

【问题讨论】:

  • 为什么要在图标出现时抛出自定义异常?在这种情况下,它将如何进入错误处理程序?当然,如果 Icon 存在,FindElement 可以正常工作并且不会引发异常。
  • 为什么不捕获所有异常然后做一些if (ex is NoSuchElementException){ //Continue;}else{throw ex;}

标签: c# selenium automated-tests


【解决方案1】:
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");
}

【讨论】:

    【解决方案2】:

    好的,我不确定这是否是您想要的,因为您在文本中询问的内容与您的代码不同。这段代码捕获所有异常,如果异常是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(Exception ex)
    {
        //Catches every exception
        if(ex is NoSuchElementException)
        {
            //Do nothing, if there's no icon your code will continue as if nothing happened
            //Or throw a custom exception for this case
        }
        else
        {
            //If there's an icon throw the exception
            //Here you can throw a custom exception
            throw ex;
        }
    }
    

    【讨论】:

    • 这两个建议正是我所需要的!非常感谢你们!
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多