当元素不存在时使用 Selenium (C#) 的 IF ELSE 条件

IF ELSE condition with Selenium (C#) when an element is not present

我在 NUNit 框架上将 Selenium 与 C# 结合使用,我试图放置一个条件语句来寻找元素(具体来说是横幅)。我已经有一段代码可以单击该横幅并继续我的测试流程。

现在,我遇到的情况是,如果该横幅不存在,则用户必须执行额外的步骤来设置横幅并继续。

所以,我希望我的 IF 检查不存在的条件以执行那段代码,否则将跳过它。

var banner = FindElement(By.Id("bannerId"));
IF ( checking if above element not present)
{ execute set of steps to set the banner }
ELSE 
{
WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
 wait2.Until(ExpectedConditions.ElementIsVisible(By.Id("bannerId")));

banner.Click();
Thread.Sleep(2000);
}

我希望我能够解释我的问题,如果有任何帮助,我将不胜感激。

你可以使用 try and catch,

try
{
    var banner = FindElement(By.Id("bannerId"));
    IF ( checking if above element not present)
    { execute set of steps to set the banner }
    ELSE 
    {
       WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
       wait2.Until(ExpectedConditions.ElementIsVisible(By.Id("bannerId")));

       banner.Click();
       Thread.Sleep(2000);
    }
}
catch(Exception ex)
{
    //check what will be the return message from ex.Message
    //and from here you could add a logic what would be your next step.
}

试试这个代码:

public bool IsElementVisible(IWebElement element)
{
    return element.Displayed && element.Enabled;
}

IF(IsElementVisible(banner) == false)
{ execute set of steps to set the banner }

我已经验证了你的代码。我可以看到一些错误。请找到以下建议:

  1. 您的代码行:

    var banner = FindElement(By.Id("bannerId")); 将抛出“NoSuchElementException”而下一行的if语句将不会被执行。因此,最简单的选择是在找到元素的地方使用 try 和 catch 并跳过 if 块。

您的代码片段可以是:

 try   
{
var banner = FindElement(By.Id("bannerId"));
WebDriverWait wait2 = new WebDriverWait(driver, 
TimeSpan.FromSeconds(40));
wait2.Until(ExpectedConditions.ElementIsVisible(By.Id("bannerId")));
banner.Click();
Thread.Sleep(2000);
}
 catch (NoSuchElementException ex)
{
  //Give the appropriate message
}
  1. 如果您想遵循您在代码中提到的方法,请尝试下面的代码片段。您必须将元素存储在列表中并检查列表大小。如果列表的大小不为零,那么您可以单击横幅,否则会显示相应的消息。

第二个代码片段:

IList<IWebElement> banner = driver.FindElements(By.Id("bannerId"));
IF ( list size is zero)
 { execute set of steps to set the banner }
 ELSE 
{
 WebDriverWait wait2 = new WebDriverWait(driver, 
TimeSpan.FromSeconds(40));
wait2.Until(ExpectedConditions.ElementIsVisible(By.Id("bannerId")));
//Click on the first element of the list
}

改用FindElements,它会防止异常,您可以检查返回集合的大小以检查横幅是否存在

IList<IWebElement> elements = driver.FindElements(By.Id("bannerId")).ToList();
if(elements.Count == 0)
{
    do something
}
else 
{
    //do something with the banner at elements[0]
    wait2.Until(ExpectedConditions.ElementToBeClickable(elements[0])).Click();
}