-1

Seems like there's an ExpectedCondition.Or() method in selenium for other languages, but I could not find it in DotNetSeleniumExtras.WaitHelpers for .NET

Is there any way to verify if one of two elements exist using Selenium with .NET?

2 Answers2

1

There are several ways to do this.

  1. Put the "OR" into your locator. An example with CSS selectors is to add a , in the locator. If you want to find the element with the ID element1 or the ID element2, then you can use the CSS selector #element1, #element2. There's an OR operator in XPath if you want that also. See this as one example.

  2. You can write your own custom condition that takes an array of locators (in case you want to look for more than just two).

    public Func<IWebDriver, IWebElement> AnyElementExists(By[] locators)
    {
        return (driver) =>
        {
            foreach (By locator in locators)
            {
                IReadOnlyCollection<IWebElement> e = _driver.FindElements(locator);
                if (e.Any())
                {
                    return e.ElementAt(0);
                }
            }
    
            return null;
        };
    }
    

    and then call it like

    By[] locators = { By.Id("element1"), By.Id("element2") };
    IWebElement foundElement = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(AnyElementExists(locators));
    

    and then foundElement is the first element found that matches your locators. There may be more than one that matches, but this would be the first. You can alter the method to do whatever else you want or add more, etc. depending on your scenario.

JeffC
  • 22,180
  • 5
  • 32
  • 55
0

You can use custom condition

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until<bool>((d) =>
{
    return d.FindElements(firstBy).Count > 0 || d.FindElements(secondBy).Count > 0;
});
JeffC
  • 22,180
  • 5
  • 32
  • 55
Guy
  • 46,488
  • 10
  • 44
  • 88