Skip to content

Locating an element

Ondřej Machulda edited this page Aug 23, 2022 · 2 revisions

Locating an element on webpage is one of the most used operation when using Selenium. There are several ways how to accomplish this with php-webdriver.

(When used in examples below, consider $driver as an instance of RemoteWebDriver.)

Locators

There are several locator strategies for locating an element which could be used in php-webdriver.

To use the locator, you must create its instance using methods of WebDriverBy class:

  • Css selector - WebDriverBy::cssSelector('h1.foo > small')
  • Xpath - WebDriverBy::xpath('(//hr)[1]/following-sibling::div[2]')
  • Id - WebDriverBy::id('heading')
  • Class name - WebDriverBy::className('warning')
  • Name attribute (on inputs) - WebDriverBy::name('email')
  • Tag name - WebDriverBy::tagName('h1')
  • Link text - WebDriverBy::linkText('Sign in here')
  • Partial link text - WebDriverBy::partialLinkText('Sign in')

For complete documentation see methods annotations or API documentation.

Locating single element

To locate a single element, use findElement() method and pass it the WebDriverBy instance.

$element = $driver->findElement(WebDriverBy::cssSelector('div.header'));
// $element will be instance of RemoteWebElement

$headerText = $element->getText();

If there are multiple elements matching the selector, only the first one is returned.

If there is none element matching, an exception will be thrown (NoSuchElementException).

Locating multiple elements

To locate multiple elements, use findElements() method and pass it the WebDriverBy instance.

$elements = $driver->findElements(WebDriverBy::cssSelector('ul.foo > li'));
// $elements is now array - containing instances of RemoteWebElement (or empty, if no element is found)

foreach ($elements as $element) {
    var_dump($element->getText());
}

If none element matches when using the findElements() method, an empty array is returned (but no exception is thrown, unlike when using findElement() method - see above).

Waiting for an element

You may need to wait until the element appears (eg. until it is rendered with javascript, or loaded with AJAX etc.). Then you can wait and find the element(s) like this:

$element = $driver->wait()->until(
    WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::cssSelector('div.bar'))
);
$elements = $driver->wait()->until(
    WebDriverExpectedCondition::presenceOfAllElementsLocatedBy(WebDriverBy::cssSelector('ul > li'))
);

Similarly behaves also methods conditions visibilityOfElementLocated, visibilityOf, stalenessOf and elementToBeClickable.

See page HowTo Wait for comprehensive information about waiting for elements or other conditions.