public static WebElement loopFindOrRefresh ( int maxRefreshes , By locator , WebDriver driver ) { for ( int i = 0 ; i < maxRefreshes ; i ++ ) { WebElement element ; try { // implicitly wait element = driver . findElement ( locator ) ; // if no exception is thrown, then we can exit the loop return element ; } catch ( NoSuchElementException e ) { // if implicit wait times out, then refresh page and continue the loop logger . info ( "after implicit wait, element " + locator + " is still not present: refreshing page and trying again" ) ; Navigation . refreshPage ( driver ) ; } } return null ; }
Implicitly wait for an element . Then if the element cannot be found refresh the page . Try finding the element again reiterating for maxRefreshes times or until the element is found . Finally return the element .