Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I'm working on a Java Selenium-WebDriver. I added

driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

and

WebElement textbox = driver.findElement(By.id("textbox"));

because my Applications takes few seconds to load the User Interface. So I set 2 seconds implicitwait. but I got unable to locate element textbox

Then I add 

Thread.sleep(2000);

Now it works fine. Which one is a better way?

1 Answer

0 votes
by (62.9k points)

Well, there are two types of wait: explicit and implicit wait. The idea of explicit wait is

WebDriverWait.until(condition-that-finds-the-element);

The concept of implicit wait is

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

In such situations I'd prefer using explicit wait (fluentWait in particular):

public WebElement fluentWait(final By locator) {

    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);

        }

    });

    return  foo;

};

fluentWait function returns your found web element. From the documentation on fluentWait: an implementation of the Wait interface which will have its timeout and polling interval organized on the fly. Each FluentWait instance defines the utmost quantity of your time to wait for a condition, as well because the frequency with which to see the condition. Moreover, the end-user might configure the wait to ignore specific kinds of exceptions while waiting, one of the exceptions could be NoSuchElementExceptions when searching for an element on the page.Usage of fluentWait in your case would be like the following:

WebElement textbox = fluentWait(By.id("textbox"));

This approach is better as you do not know exactly how much time to wait and in polling interval, you can set arbitrary time value which element presence will be verified through. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...