Selenium – Keep on refreshing the page until certain element to appear

selenium

I have a scenario like, i want to keep on refreshing the page until some element to appear in the page. Can anyone please help me on the same?

I am using the below code for the same but the page is not refreshing after five second

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

           WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
             public WebElement apply(WebDriver driver) {
               return driver.findElement(locator);
             }
           });

Thanks

Sudhansu

Best Solution

Try using the FluentWait class.

   // Waiting 30 seconds for an element to be present on the page, checking
   // for its presence once every 5 seconds.
   Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

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

In that way Selenium will just wait for a certain period of time until certain elements have been loaded.

I hope that will solve your problem so you don't have to refresh the page.

Edited:

As MrTi so friendly points out, the above code will not refresh your page. It will only wait for a certain period of time until certain elements have been loaded. I just thought it might solve the problem, without you having to refresh the page. If that does not solve your problem and you still need to refresh your page, then you need to add driver.navigate().refresh() before the return, like this:

   // Waiting 30 seconds for an element to be present on the page, checking
   // for its presence once every 5 seconds.
   Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
     public WebElement apply(WebDriver driver) {
       driver.navigate().refresh()
       return driver.findElement(By.id("foo"));
     }
   });
Related Question