Skip to content

Example command reference

Ondřej Machulda edited this page Sep 22, 2022 · 62 revisions

Example command reference

This is a list of most-used php-webdriver commands.

NOTE: examples below are done shorthand, with an instance of WebDriver in $driver variable.

To see a full scenario, have a look at example.php.

Open a webpage

$result = $driver->get('https://www.google.com/');

Working with elements

Locating an element

// Locate single element:
$element = $driver->findElement(WebDriverBy::cssSelector('div.header'));

// Locate multiple elements:
$elements = $driver->findElements(WebDriverBy::cssSelector('ul.foo > li'));

Read more information on dedicated wiki page Locating an element.

Get text of an element

$result = $driver->findElement(WebDriverBy::id('sign-in'))->getText();

Get attribute of an element

As an "attribute" is considered what is declared in the HTML markup of the element. To get the value of "property" (like innerHTML), see "Get property of an element" method below.

$title = $driver->findElement(WebDriverBy::id('sign-in'))->getAttribute('title');

// Get value of an input/textarea element
$inputElement = $driver->findElement(WebDriverBy::id('username'));
$value = $inputElement->getAttribute('value');

Get property of an element

To read an IDL ("Interface Description Language") value of "JavaScript" property of an element (for example innerHTML, childElementCount etc.). See MDN for list of available element properties.

$title = $driver->findElement(WebDriverBy::id('sign-in'))->getDomProperty('innerHTML');

Click an element (link, checkbox, etc.)

$driver->findElement(WebDriverBy::id('sign-in'))->click();

Trigger mouseover event (hover)

$element = $driver->findElement(WebDriverBy::id('some_id'));
$driver->getMouse()->mouseMove($element->getCoordinates());

Check if an element is visible

$element = $driver->findElement(WebDriverBy::id('element id'));
if ($element->isDisplayed()) {
    // do something...
}

Shadow DOM

Shadow DOM is essential part of Web Components, as it encapsulates and isolates the component DOM and styles. This component isolation however mean one cannot access elements which are encapsulated in shadow DOM of a component with usual $driver->findElement() or $driver->findElements() methods.

To access these elements, php-webdriver provides specific methods:

// consider having web component <custom-element>...</custom-element> with its inner DOM like <input>

// first, locate the element of the Web Component, which is part of the standard DOM
$element = $this->driver->findElement(WebDriverBy::cssSelector('custom-element'));

// get element's shadow, which is the base for accessing encapsulated elements
$shadowRoot = $element->getShadowRoot();

// ShadowDom instance now provide findElement() and findElements() methods, which will target only elements inside this Shadow DOM
$elementInShadow = $shadowRoot->findElement(WebDriverBy::cssSelector('input'));

Forms

Type into text field (input, textarea...)

$driver->findElement(WebDriverBy::id('element id'))->sendKeys('I want to type this');

Clear the existing value in text field

If a text field already has a non-empty value and you want to update that field, here's how to clear the existing value:

$driver->findElement(WebDriverBy::id('element id'))->clear();

Check if selectable element (checkbox, radio, option...) is selected

This operation only makes sense on input elements of the checkbox and radio-button states, or on <option> elements.

$checkboxElement = $driver->findElement(WebDriverBy::id('myCheckbox'));
if ($checkboxElement->isSelected()) {
    // ...
}

You can use helper classes to simplify interaction with this kind of form elements - see below.

Interacting with special form elements (<select>, checkboxes, radio buttons)

For simple operations, like checking single checkbox, you can use click() method:

$driver->findElement(WebDriverBy::id('terms_agree'))->click();

However, to simplify more complex tasks, like selecting one of many options, getting selected options etc., php-webdriver contains helper classes:

$selectElement = $driver->findElement(WebDriverBy::name('language-select'));
$select = new WebDriverSelect($selectElement); // use WebDriverRadio for radio buttons or WebDriverCheckboxes for check boxes

// Get value of first selected option:
echo $select->getFirstSelectedOption()->getText();

// Get all selected options - useful when dealing with multi-select
$selectedOptions = $select->getAllSelectedOptions();

// Select option
$select->selectByValue('fr');
$select->selectByIndex(1);
$select->selectByVisibleText('Czech');
$select->selectByVisiblePartialText('UK');

// ...

See wiki page Select, checkboxes, radio-buttons for more details and examples.

Submit a form

Form could be submitted either by calling submit() method on the form element, on any of the form's input elements or it could be triggered by clicking (using click()) on a submit button.

<form id="myForm" method="post">
    <input type="text" name="query">
    <input type="submit" name="submit" value="Submit">
</form>
$driver->findElement(WebDriverBy::id('myForm'))
    ->submit(); // submit event called on the whole form
$driver->findElement(WebDriverBy::name('query'))
    ->submit(); // submit event could be called on any of the form elements
$driver->findElement(WebDriverBy::name('submit'))
    ->click(); // submit triggered using a click on submit button

Alerts, confirmations and prompts

See dedicated wiki page with more examples.

Alerts

$driver->switchTo()->alert()->dismiss(); // dismiss
$driver->switchTo()->alert()->getText(); // get alert text, works for confirmations and prompts

Confirmations

$driver->switchTo()->alert()->accept(); // accept
$driver->switchTo()->alert()->dismiss(); // dismiss

Prompts

$driver->switchTo()->alert()->sendKeys('Test'); // enter text
$driver->switchTo()->alert()->accept(); // submit

$driver->switchTo()->alert()->dismiss(); // dismiss

Page navigation

Reload the page

$driver->navigate()->refresh();

Go to previous page

$driver->navigate()->back();

More methods related to navigation can be found in WebDriverNavigation class.

Windows, tabs, frames, iframes

See dedicated page with more examples.

Browser window

// Maximize
$driver->manage()->window()->maximize();

// Set fullscreen mode (this obviously does not have any effect in headless mode)
$driver->manage()->window()->fullscreen(); 

// Get window size
$windowDiemensions = $this->driver->manage()->window()->getSize();
echo 'Window dimensions: ' . $windowDiemensions->getWidth() . 'x' . $windowDiemensions->getHeight(); // output something like "Window dimensions: 800x600"

// Set window size to 800x600 px
$driver->manage()->window()->setSize(new WebDriverDimension(800, 600));

Window handling

Getting current window handle

"Window handle" is unique identifier of every top-level browsing context (window or tab).

$handle = $session->getWindowHandle();

Getting all window handles

$handles = $session->getWindowHandles();

Switching to window by its handle

$driver->switchTo()->window($handle);

Open a new tab or window

$driver->switchTo()->newWindow(); // window type (new tab or new window) could be passed as optional argument

See more details and examples on window handling.

Frames, iframes

// Find an iframe element
$iframe = $session->findElement(WebDriverBy::tagName('iframe'));

// Switch to iframe inside this element
$session->switchTo()->frame($iframe); // you can also identify frame by its number (frame identifier)

// Do whatever you needed to do in the frame/iframe

// Go back to the main document
$session->switchTo()->defaultContent();  // this is the same as $session->switchTo()->frame();

See more examples.

Executing JavaScript via WebDriver

Synchronous script execution

Inject a snippet of JavaScript into the page for execution in the context of the currently active page/frame. The executed script is assumed to be synchronous and the result of evaluating the script will be returned.

$session->executeScript('document.body.style.backgroundColor = "red";'); // this will set document background to red

$scriptResult = $session->executeScript('return document.title;'); 
// $scriptResult now contains page title

You may also pass elements to the JavaScript code you are executing as a second argument of executeScript() or executeAsyncScript(). Inside the script they will be available in arguments array:

$element1 = $driver->findElement(WebDriverBy::cssSelector('.foo'));
$element2 = $driver->findElement(WebDriverBy::cssSelector('.bar'));

$this->driver->executeScript('
    var element1 = arguments[0];
    var element2 = arguments[1];
    element1.innerHTML = 'foo';
    // ...
    ',
    [$element1, $element2]
);

Asynchronous script execution

The driver will pass a callback as the last argument to the snippet, and block until the callback is invoked.

You may need to define script timeout using setScriptTimeout() method of WebDriverTimeouts first.

$this->driver->manage()->timeouts()->setScriptTimeout(5);
$scriptResult = $session->executeAsyncScript('
    var callback = arguments[arguments.length - 1];
    // do something, the PHP script execution will be blocked until you call callback()
    callback("you can also return something using this callback");
');

// $scriptResult now contains the returned text

Screenshots

Screenshot of current view

// Save to file:
$driver->takeScreenshot('screenshot.png');

// Store in variable:
$screenshotData = $driver->takeScreenshot();

Screenshot of an element

$element = $driver->findElement(WebDriverBy::id('some_id'));

// Save to file:
$element->takeElementScreenshot('element-screenshot.png');

// Store in variable:
$elementScreenshotData = $element->takeElementScreenshot();

Custom commands

Php-webdriver also allows sending any custom command. This may be useful for some browser specific commands, which are not directly implemented in php-webdriver.

Clone this wiki locally