Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check element exists using PHP Selenium 2 Webdriver?

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"}

like image 201
condo1234 Avatar asked Oct 21 '13 14:10

condo1234


People also ask

How do you check if an element is present in Selenium?

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.

Can I use Selenium with PHP?

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.

How do I verify that an element does not exist in Selenium?

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.


2 Answers

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';
}
like image 54
whhone Avatar answered Sep 30 '22 15:09

whhone


Use: $driver->findElements intstead of findElement

findElements will return an empty array if element not exists and will not throw an exception.

like image 37
Amit Rana Avatar answered Sep 30 '22 13:09

Amit Rana