Check that the element is clickable or not in Selenium WebDriver

SeleniumAutomation TestingTesting Tools

We can check if the element is clickable or not in Selenium webdriver using synchronization. In synchronization, there is an explicit wait where the driver waits till an expected condition for an element is met.

To verify, if the element can be clicked, we shall use the elementToBeClickable condition. A timeout exception is thrown if the criteria for the element is not satisfied till the driver wait time.

Syntax

WebDriverWait wt = new WebDriverWait(driver, 5);
wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy")));

We have to add - import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait statements to implement ExpectedConditions in our code.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElemntClickable{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      WebElement n=driver.findElement(By.className("mui-btn"));
      n.click();
      // explicit wait
      WebDriverWait wt = new WebDriverWait(driver,6);
      // elementToBeClickable expected criteria
      wt.until(ExpectedConditions.elementToBeClickable (By.className("s-buy")));
      System.out.println("Current page title:" + driver.getTitle());
      driver.close();
   }
}

Output

raja
Published on 06-Apr-2021 11:20:41
Advertisements