I am trying to check if an element on a page exists by CSS using Selenium 2. Anyone have any examples using PHP Selenium Webdriver Facebook wrapper?
I have tried the below code:
if($driver->findElement(WebDriverBy::xpath("image-e4e")) != 0)
{
}
But gives me this error:
Fatal error: Uncaught exception 'NoSuchElementWebDriverError' with message 'Unable to locate element: {"method":"xpath","selector":"image-e4e"}
New Selenium IDE To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list. If the size is 0, it means that this element is absent from the page.
The Selenium automation framework supports many programming languages such as Python, PHP, Perl, Java, C#, and Ruby. But if you are looking for a server-side programming language for automation testing, Selenium WebDriver with PHP is the ideal combination.
The findElements gives an elements list. We shall count the number of elements returned by the list with the help of the size method. If the value of size is greater than 0, then the element exists and if it is lesser than 0, then the element does not exist.
By design, findElement
returns the WebDriverElement if it is found but it throws an exception when it is not found.
To check whether the element is on the page without getting an exception, the trick is to use findElements
. findElements
returns an array of all elements found on the page. It returns an empty array if nothing is found.
if (count($driver->findElements(WebDriverBy::xpath("image-e4e"))) === 0) {
echo 'not found';
}
Use: $driver->findElements
intstead of findElement
findElements will return an empty array if element not exists and will not throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With