Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload the page if element doesn't appear in selenium webdriver java

At times due to time out or other reason the page stops loading or gets loaded but the signup page doesn't appear, to make sure it appears we have to refresh the page, I have tried driver.navigate.refresh(), I have tried explicit wait and javascript executor, nothing works, I am adding the snippet of what I have tried, but it doesn't work either. My scripts fails once the findelement().isdisplayed is false, it is not going in the if loop. Below is the code-

for(int i=0;i<3;i++)
    {   
        System.out.println("In for loop");
        try
        {
        if(driver.findElement(byusername).isDisplayed())
        {
            System.out.println("Element found");
            driver.findElement(byusername).sendKeys(username);
            driver.findElement(bypassword).sendKeys(password);
            driver.findElement(signIn).click();
            System.out.println("Logged in");
            basewait.until( ExpectedConditions.presenceOfElementLocated(Tab));
            System.out.println("Wait completed, going to base class");
            i=3;
        }
        else
        {
            System.out.println("Element not found"+i+" try");
            driver.navigate().refresh();
            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
            i++;
        }
        }
        catch(NoSuchElementException e)
        {
            System.out.println(e);
        }
like image 713
kritika agarwal Avatar asked Mar 21 '26 05:03

kritika agarwal


1 Answers

Try to replace:

if(driver.findElement(byusername).isDisplayed())

with:

if(driver.findElements(byusername).size() > 0 && driver.findElements(byusername).get(0).isDisplayed())

This won't throw exception and you can go to else statement. driver.findElements(byusername) return a list of elements found and if no elements were found it returns just an empty list.

like image 178
Andrei Suvorkov Avatar answered Mar 22 '26 20:03

Andrei Suvorkov