Difference between findElement and findElements

Reporting and elements may contain errors that are not detected with FIND_ELEMENT_FAILURE: No element found.

To create this, we have used a simple scenario where we open the perfecto.io site and search for an element that is not there. In the first case, we use findElements, and in the other case, findElement. Continue to the end of the article to find out the results.

findElements method

Copy

Sample code

reportiumClient.testStart("FindElements", new TestContext("NatoTest", "findElements"));
driver.get("perfecto.io");
List<WebElement> elements1 = driver.findElementsByXPath("//*[@class=\"gLFyfg\"]");
reportiumClient.testStop(TestResultFactory.createSuccess());

Result in Perfecto Reporting:

The rror itself:

Here we see that although the expected result has not been found, the test is marked as successful.

Next, let’s see what happens when we use the findElement method.

findElement method

Copy

Sample code

reportiumClient.testStart("FindElement", new TestContext("NatoTest", "findElement"));
driver.get("perfecto.io");
WebElement element1 = driver.findElementByXPath("//*[@class=\"gLFyfg\"]");
reportiumClient.testStop(TestResultFactory.createSuccess());

Result in Perfecto Reporting:

The error itself:

Now we see that the expected result is not found AND the test is marked as failed.

Why is this happening?

As defined by Selenium WebDriver API the method findElement() should be used when the element is expected to exist. If the element doesn’t exist it is an error and the command is marked as failed. The method findElements() should be used for checking whether one or more elements, that fit the find criteria, exist. If no element is found, which is a valid situation, an empty list is returned and the command is marked as successful.