Selenium – Java, wait for web element

In many cases you need to wait for a website response to get visibility of various web elements. This means you are not able to get hold of the web element until it is visible or clickable. Most likely ending up with the selenium webdriver error:

org.openqa.selenium.NoSuchElementException: no such element: 
Unable to locate element:

Selenium has a solution for that, let’s have a look at this piece of code.

WebElement searchButton= chromeDriver.findElementByXPath("//button[contains(.,'Search')]");
WebDriverWait wait = new WebDriverWait(chromeDriver, 10);
wait.until(ExpectedConditions.elementToBeClickable(searchButton));

The example above is looking for a HTML button ‘Search’. It will wait for the button to be clickable for a maximum of 10 seconds. This is good practise for webforms where the buttons are only clickable when all the mandatory fields are fulfilled.

ExpectedConditions.elementToBeClickable(searchButton)

The ExpectedConditions has enormous methods to fulfill your needs. Have a look at the API.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s