Why does a list of WebElements with size 0 not throw any exception while locating those WebElements?


I was trying to get a list of WebElements from a website. On printing its size, it turned out to be zero, which means the expected WebElements were not found hence while locating those WebElements(using Xpath), why didn’t the system throw any exception when the elements were missing?


The reason the script doesn’t throw an error is the way FindElements and FindElement are implemented by Selenium

To give a reference refer the Implementation of FindElements by selenium https://github.com/SeleniumHQ/selenium/blob/702b3aae7385adf331d75cdeacd79720cf6b9c84/java/src/org/openqa/selenium/remote/ElementLocation.java#L171-L191

On line 181 in the above link you will see a check where if the element is null it will return an Collections.emptyList();

On contrary for FindElement implementation by selenium

In the above link you will see a similar check at line 164 for if the element is null but for the check an error Unable to find element with locator is raised

If you require to assert whether the element was located by FindElements you can check the length of the list return by FindElements before performing any action on the element

Answered By – Darshan Shah

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published