Check my code of a method that I use to wait for elements in selenium webdriver I call it in this way waitForElement(By.id(idOfElement));
public void waitForElement(By by) {
for (int second = 0;; second++) {
//System.out.println("seconds : " + second);
if (second >= 15) {
System.out.println("element not found");
break;
}
try {
if (driver.findElement(by).isDisplayed()) {
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
//System.out.println("found element before click");
driver.findElement(by).click();
//System.out.println("found element after click");
return;
}
} catch (Exception e) {
// e.printStackTrace();
//System.out.println("inside exception");
}
}
//System.out.println("click on element after being not found");
driver.findElement(by).click();
}
this method should find element and clicks on it
it worked fine and it was supposed to click the element then return from the method but now it fails because driver clicks the element which redirects to another page and after new page appears driver instead of returning from method it enters the catch exception and finally code fails because driver trying to find that element that was in previous page
any help to fix this method?
Update: There is a return after the first click If the element was found it should go out of the method the problem here is that sometimes executing code finds the element and clicks it and don't reach the code after the first click (which is return;) And I used this method to avoid exception of element not found because sometimes I use waits and elements exists but code fails because the element wasn't found or because of an exception says "time out receiving message from renderer"