Search code examples
javaseleniumloopsselenium-webdriverwebdriverwait

I want to refresh my browser until my login page appears - JAVA -Selenium


I need to refresh my web page until a certain item appears in my webpage. I cannot simply use the find element statement since the item only appears after some time(2-6min) and only when the page has been refreshed. ** Now I need to create a loop in which the site keeps refreshing until it gets a lands on the login page (I am using login button for verification in below code). When it finds the element I then can select continue my test. also I need handle one case, in case if I get 404 error**(//body[contains(text(),'404 - Not Found')]) I want to terminate my loop and should fail the test case.

Can someone assist me with this issue or give me advice on how to create the same outcome but then with a better approach? Much appreciated

The below code I tried but it's an endless loop and cannot handle 404 error

driver.navigate().to(AppUrl);

!Boolean elementFound = false;
        do { 
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        try { 
            elementFound = driver.findElement(By.xpath("//*[@id='btnLogin']")).isDisplayed(); 
        } catch (NoSuchElementException e){ 
            
        }
        driver.navigate().refresh(); 
        } while (!elementFound);   
        driver.findElement(By.xpath("//*[@id=\"userID\"]")).sendKeys(UserId);

Solution

  • Simply you can do with below code:

    driver.navigate().to(AppUrl);    
    int size;
        do{
            if(driver.findElement(by.xpath("//body[contains(text(),'404 - Not Found')]")).getText().contains("404 - Not Found")){
                //Script status fail
                break;
            }else{
                size = driver.findElements(by.xpath("//*[@id='btnLogin']")).size();
                if(size == 0){
                driver.navigate().refresh();
                }else{
                    break;
                }
            }
        }while(size < 1);