'how to check whether button is present or not in selenium webdriver?

I tried with below code,

if(driver.findElement(By.xpath("(//button[@type='button'])[2]")).isDisplayed()) 
{
     driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
}

else
    System.out.println("Show more is not there");

Here, if there is "Show more" button in application, it's executing correctly but when the "Show more" button is not there, it's not executing else part and showing "Unable to locate element error" Can anyone please help in this ? Thanks in advance.



Solution 1:[1]

Selenium throws an exception when not able to find and element using findElement so you will need to use try / catch blocks -

try 
{
     if(driver.findElement(By.xpath("(//button[@type='button'])[2]")).isDisplayed()) 
     {
          driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
     }
}
catch (ElementNotFoundException | ElementNotVisibleException | NoSuchElementException)
{
    System.out.println("Show more is not there");
}

Solution 2:[2]

There are two different methods to find out if a WebElement is present at the page. The first one is to catch the exception like in the other answer or to make a list like:

List<WebElement> resultList = findElements(By.xpath("(//button[@type='button'])[2]"));

and then check the size of the list:

resultList.size() = 0;

so in your example it would be:

List<WebElement> resultList = findElements(By.xpath("(//button[@type='button'])[2]"));
if(resultList.size() > 0){
     driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
}else{
    System.out.println("Show more is not there");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vikas Ojha
Solution 2 spcial