Tips and tricks to find an element - Selenium

In this section, we are going to look at some tips and tricks that might be of use when trying to find elements on the page. We can also apply them to see if the elements are not on the page.

Finding if an element exists without throwing an error

Selenium WebDriver is really good at letting you know when an element does not exist. If it throws a NoSuchElementException, then we know it's not there. Unfortunately I, and many others, have not been big fans of using exception handling as a way of flow control.

To get around this we can use the findElements() call, and then we just need to check that the size of the list returned is 0. For example:

List<WebElement> elements = driver.findElements( By.Id("myElement")); elements.size(); //This should be zero and can be checked accordingly

Waiting for elements to appear on the page

Web applications now want to appear as though they are desktop applications as more and more people move to hardware like tablets or netbooks which have very small hard drives. This is all done through AJAX to the page.

This means that when we are working with Selenium WebDriver we need to have it synchronized with what is happening on the page. We do not want to use something like Thread.sleep() because that doesn't make our tests run as quickly as possible. We need to use one of the next two approaches: implicit or explicit waits.

Implicit waits

Selenium WebDriver has borrowed the idea of implicit waits from Watir. This means that we can tell Selenium that we would like it to wait for a certain amount of time before throwing an exception that it cannot find the element on the page. We should note that implicit waits will be in place for the entire time the browser is open. This means that any search for elements on the page could take the time the implicit wait is set for.

Let's see how we can use this.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Selenium Topics