user2464219 user2464219 - 2 months ago 19
C# Question

Selenium WebDriver - If element present select it, if not ignore it and continue to next element

I am just finishing a test script and accessing a fairly dynamic page. The page in question, has an element appear (generally a radio button or tick-box), which is only present if certain criteria in previous pages are met. So, my test will be accessing this page irrelevant of previous criteria and I want to hit the "continue" element at the bottom of the page whilst handling these elements "IF" they appear. I have a few method sto click elements by ID, and so far have the following code:

// Selects the "Confirm" button
IWebElement radioOption = mWebDriver.FindElement(By.Id("Radio_Button_Id"));
if (radioOption.Displayed)
{
this.ClickElementById("Radio_Button_Id");

// Clicks CONTINUE
this.ClickElementById("CONTINUE");
}
else
{
// Selects CONTINUE
this.ClickElementById("CONTINUE");
}


I am trying in this code to handle that if the radio button appears, select it then select the continue button. Also, if the radio button does not appear, ignore it and select the continue button. Any help with this would be much appreciated.

Answer

Try something like this:

//Displayed
public static bool IsElementDisplayed(this IWebDriver driver, By element)
{
    IReadOnlyCollection<IWebElement> elements = driver.FindElements(element);
    if (elements.Count > 0)
    {
        return elements.ElementAt(0).Displayed;
    }
    return false;
}

//Enabled
public static bool IsElementEnabled(this IWebDriver driver, By element)
{
    IReadOnlyCollection<IWebElement> elements = driver.FindElements(element);
    if (elements.Count > 0)
    {
        return elements.ElementAt(0).Enabled;
    }
    return false;
}

You'll not get any exception and then the test can continue.

Comments