Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium webdriver explicit wait

I'm writing some automated tests for using the selenium chrome driver. I trying to write a reusable method that will explicitly wait for elements to appear and then call this method in other classes. Seems pretty straight forward but its not doing what I want it do. Here is the method that I have.

public String waitForElement(String item) {
    WebDriverWait wait = new WebDriverWait(driver,30);
    WebElement element = wait.until(
                        ExpectedConditions.elementToBeClickable(By.id(item)));
    return item;
}

Then I call the method and pass it a parameter like this:

waitForElement("new-message-button");

That doesn't seem to become working, can someone give some insight?

like image 668
vslat Avatar asked Feb 03 '26 20:02

vslat


2 Answers

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});

Check this TUTORIAL for more details.

like image 106
anuja jain Avatar answered Feb 05 '26 10:02

anuja jain


public static void clickOn(WebDriver driver, WebElement locator, int timeout)
 {
        new WebDriverWait(driver,timeout).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(locator));
        locator.click();

    }

Call the above method in the main method then we will get explicitly wait functionality.

like image 28
prasadraj d Avatar answered Feb 05 '26 09:02

prasadraj d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!