-1

Please comment the following code I found on YouTube. It checks whether an element is present at the time

public boolean isElementPresent(By locator)
    {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
        List<WebElement> list = driver.findElements(locator);
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        if (list.size() == 0)
            return false;
        else
            return list.get(0).isDisplayed();
    }

It dynamically changes implicitlyWait in the method. In all Selenium resources are always stated that the implicitWait can be set only once in the test class. The code above is similar to some extent to the explicit wait since it adapts to different situations. What is your opinion about this code?

In the Selenium documentation it is said that Once set, the implicit wait is set for the life of the session. However, in the code above we change the implicitlyWait twice. Is the documentation wrong?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Vladimir
  • 630
  • 3
  • 12
  • 26

1 Answers1

0

Implicit wait

The Implicit wait is to notify the WebDriver instance to poll the HTML DOM for a certain amount of time when trying to find an element or elements if they are not immediately available within the DOM Tree.


Once set, the implicit wait is set for the life of the session

Yes, you saw it right. That's because implicit waits are implemented on the remote side of the WebDriver system. That means they are baked in to GeckoDriver, ChromeDriver, IEDriverServer, etc WebDriver variants that gets installed into the anonymous Firefox/Chrome profile, and the Java remote WebDriver server. However, you can always re-configure the implicitlyWait.

You can find a detailed discussion in Using implicit wait in selenium


This usecase

Syntactically, your code is flawless. Ideally, you would set the implicitlyWait while looking out for the desired elements. Once the elements are ideantified and stored in a list you can reset the implicitlyWait back to 0. So effectively your code block will be:

public boolean isElementPresent(By locator)
{
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    List<WebElement> list = driver.findElements(locator);
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    if (list.size() == 0)
        return false;
    else
        return list.get(0).isDisplayed();
}
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352