Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
user2464219 Avatar asked Sep 10 '13 11:09

user2464219


2 Answers

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.

like image 143
Tedesco Avatar answered Sep 28 '22 06:09

Tedesco


You said that you were getting NoSuchElementExceptions. radioOption.Displayed tests to see if the element is visible on the page, but it will throw an error if the element doesn't even exist. (An element can be present, but invisible)

To test to see if an element is present, you need to do mWebDriver.FindElements (note the S). This will return a List<WebElement> of all of the elements that match your selector, and if it can't find any, it will return a list of size 0 (and not throw an error).

That way, your if statement will be if (radioOptions.size()!=0), and will check to see if the element exists (not if its visible).

like image 32
Nathan Merrill Avatar answered Sep 28 '22 06:09

Nathan Merrill