Arun
Arun

Reputation: 875

What is the alternative of selenium.isElementPresent in Webdriver

Hi I need to check a drop down field is having given values but those values are not selected so its not getting displayed in the dropdown box. I have following Xpath for the element

//table[contains(@id,'Field')]//tr[td//span[text()='Code']]/preceding-sibling::*[1]/td//select[contains(@id,'GSRCH_FLT')]/option[text()='not=']

which is identifying the element properly in the browser. But when I am using the following webdriver method to verify it

driver.findElement(By.xpath("//table[contains(@id,'Field')]//tr[td//span[text()='Code']]/preceding-sibling::*[1]/td//select[contains(@id,'GSRCH_FLT')]/option[text()='not=']")).isDisplayed();

its returning false since it is not getting displayed in the box.

Can u tell me the alternative for this.

Upvotes: 5

Views: 21293

Answers (4)

The Recruit
The Recruit

Reputation: 863

I found out that WebDriver does not have a function called isElementPresent(). This was one of the important functions that was used in Selenium-1.0. To implement this in WebDriver you just need to write a method as mentioned below. You can then use this function with any type of By (By.id, BY.name, etc.)

private boolean isElementPresent(WebDriver driver, By by){
  try{
    driver.findElement(by);
    return true;
  }catch(NoSuchElementException e){
    return false;
  }
}

And here is an example of how you would call this function

if (isElementPresent(by.id("btnSubmit")) {
   // preform some actions
}

The above function will return true in case the element is found on the page, else it will return false.

Upvotes: 4

Ross Patterson
Ross Patterson

Reputation: 9569

You want:

private boolean isElementPresent(WebDriver driver, By by){
    return driver.findElements(by).count != 0;
}

findElements() is better for this than findElement() because it won't wait if the element isn't present. If you're running with implicit waits turned on, findElement() will time out looking for the element (that's the exception you're catching), and it will take a while.

Upvotes: 8

Arun
Arun

Reputation: 1

Use isDisplayed() for verifying whether an element is available on the page.

Upvotes: 0

Eelke
Eelke

Reputation: 21

    internal static bool IsElementPresent(IWebDriver driver, By by, int timeoutSeconds=10)
    {

        for (int second = 0; second< timeoutSeconds ; second++)
        {
            try
            {
                driver.FindElement(by);
            }
            catch (NoSuchElementException e)
            {
                Thread.Sleep(1000);
                continue;
            }

            return true;
        }

        return false;

    }

Upvotes: 0

Related Questions