Check element exists using PHP Selenium 2 Webdriver?
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.
You can also use the sizeof()
builtin function in PHP:
$check = $driver->findElements(WebDriverBy::xpath('image-e4e'));if (sizeof($check) > 0) { echo "success";}
OR can also be used to count()
function:
if (count($driver->findElements(WebDriverBy::xpath('image-e4e'))) > 0) { echo "success";}
Output: If XPath element is available on a page then it will give you success
If you want to use findElement
then:
$checkXpath = 'image-e4e';$checkXpath = $this->findElementByXpath($driver, $checkXpath);$check = $driver->findElement($checkXpath);if (count($check) > 0) { echo "success";}
OR
$checkXpath = WebDriverBy::xpath('image-e4e');$check = $driver->findElement($checkXpath);if (count($check) > 0) { echo "success";}
Output: If XPath element is available on a page then it will give you success
Note: The findElement
method throws a NoSuchElementException exception when the element is not available on the page. Whereas, the findElements
method returns an empty list when the element is not available or doesn't exist on the page.