hs17
hs17

Reputation: 13

How to click an element if it is found before the wait time expires in selenium java?

When I search for a term, sometimes the search result is displayed immediately. I have a wait where it waits for 10 seconds to click the element even if the result is found before it.

How to click the element as soon as the search result is displayed?

Upvotes: 1

Views: 1573

Answers (2)

Andrei
Andrei

Reputation: 5637

You can use this:

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

The sample could be like this:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));

This code wil wait until the element will be clickable at least 10 seconds. More information you can get in the documentation here.

According your explanation, you can do like this:

List<WebElement> listSearchResults = new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfAllElementsLocatedBy((By.xpath(""))));
if(listSearchResults.size() > 1){
  new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(listSearchResults.get(listSearchResults.size()-1))).click();
}

Upvotes: 1

dangi13
dangi13

Reputation: 1275

You can use :

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("your selector")));

It will wait for visibility of the element and once it is visible you can click it . i.e

driver.findElement(By.xpath("your selector")).click();

Hope that helps you:)

Upvotes: 0

Related Questions