Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)
edited by

I'm trying to make Selenium wait for an element that is dynamically added to the DOM after page load. Tried this:

fluentWait.until(ExpectedConditions.presenceOfElement(By.id("elementId"));

 In case it helps, here is fluentWait:

FluentWait fluentWait = new FluentWait<>(webDriver) {

    .withTimeout(30, TimeUnit.SECONDS)

    .pollingEvery(200, TimeUnit.MILLISECONDS);

}

 But it throws a NoSuchElementException - looks like presenceOfElement expects the element to be there so this is flawed. This must be bread and butter to Selenium and don't want to reinvent the wheel... could anyone suggest an alternative, ideally without rolling my own Predicate?

1 Answer

0 votes
by (62.9k points)

In any software web application's web driver test case, you can easily wait for the presence of element using IMPLICIT WAIT. If you have used implicit wait in your test case then you do not require to write any extra conditional statement to wait for element visibility. But in some cases, if any element is taking too much time to be visible on the software web page then you can use EXPLICIT WAIT condition in your test case.

 If you have a scenario to wait till element visible on the software web page then selenium webdriver/Selenium 2 has its own method named visibilityOfElementLocated(By locator) to check the visibility of element on the software web page. We can use this method with an explicit webdriver wait condition to wait until the element visible of present on the page. 

 Syntax to wait until the element visible on the page is shown below. It will wait max 15 seconds for an element. As soon as element visible on the page, web driver will go for executing the next statement.

WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='text3']")));

Complete Code Piece:

@Test

 public void test() throws InterruptedException, IOException 

 {   

  //To wait for element visible

  WebDriverWait wait = new WebDriverWait(driver, 15);

  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='text3']")));

  

  driver.findElement(By.xpath("//input[@id='text3']")).sendKeys("Text box is visible now");

  System.out.print("Text box text3 is now visible");

    }

If you are looking for more knowledge about Selenium, you may visit Selenium tutorial and Selenium training by Intellipaat. 

Watch this video on Selenium Tutorial for Beginners

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...