You might get following error when you run above script because when Selenium will type Search Keyword, suggestions results will gonna take some time to get displayed. However, selenium will keep executing statements one by one without any break as in the above script, we haven’t used any logic which would wait for the element, if it is taking time to load and finally the script will fail. Here, the wait concept comes into picture.

Error Description

If you notice above in error Description, an error which is thrown here is NoSuchElementException. And it was thrown in just 144 Milliseconds.
This exception is thrown by findElement function.
Webdriver throws this exception, if it is unable to locate an element due to certain reasons like locator used in the script is incorrect or element is not loaded yet.

Lets use Thread.sleep() command in above script to give a specific wait of 5 seconds after typing search keyword so that Suggestions will get enough time to load and then click on the last suggestion.

Above code will execute successfully as we have given a wait of 5 seconds after typing ‘Selenium’ Keyword.

Thread.sleep disadvantages

1. Here if you notice in above script, we have given a wait of 5000 Milliseconds(5 seconds). What if, an element just take just 1-2 seconds to load as in this case, script will still wait for another 3 seconds which is bad as it is unnecessarily increasing the execution time.

2. When using Thread.sleep(), we have to mention wait time in advance, there is no guarantee that the element will be displayed in that specific wait time, there may be case when it will takes may be more than 5 seconds to load and again your script will fail. Hence, using sleep() in your script is not always the wise decision. Thread.sleep() is basically a static wait, it partially solves the problem.

In Order to overcome from the issues explained above, you would have to go with another wait concepts provided by Selenium WebDriver like implicit wait, Explicit wait and Fluent Wait.

If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.