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

Time:07-11

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?

CodePudding user response:

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 https://github.com/SeleniumHQ/selenium/blob/702b3aae7385adf331d75cdeacd79720cf6b9c84/java/src/org/openqa/selenium/remote/ElementLocation.java#L154-L168

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

  • Related