PHP-SeleniumClient V2 Documentation

Overview

Nearsoft's PHP-SeleniumClient allows the interaction with Selenium Server V2 in PHP. It communicates with the WebDriver API through the official JsonWireProtocol.


One of the goals is to provide a client usage as close as possible to the Selenium Official libraries (such as Java's, c#'s). Most methods are named as the same as of these libraries'. This way, common ideas, approaches and techniques that other people have may be implemented.


Required environment

Needed:
  • PHP 5.3.8 or higher
  • PHPUnit
  • Curl
  • Nearsoft/PHPSelenium Client
  • SeleniumHQ Jar File

PHPUnit

If you are interested in running our demos and tests PHPUnit is required, otherwise you can skip this step. For making UI tests using this library you may use PHPUnit or any other PHP testing framework of your choice.

  • Installing on Debian
  • Open up Terminal and run
    $ sudo apt-get install phpunit ### For more information check this page: http://phpunit.de/manual/current/en/installation.html

    Curl

  • Installing on debian
  • Open up a terminal and run
    $ sudo apt-get install php5-curl

    **Restart Apache**
    $ sudo /etc/init.d/apache2 restart

    For more information check this page:

    http://curl.haxx.se/docs/install.html

    Nearsoft PHPSelenium Client

    Donwload load Nearsoft PHPSelenium Client Project

    https://github.com/Nearsoft/PHP-SeleniumClient

    You may also download/install through composer and packagist

    https://packagist.org/packages/nearsoft/php-selenium-client

    SeleniumHQ JAR File

    You need to download Selenium-server-standalone JAR
    Use version 2.21.0 or newer
    http://docs.seleniumhq.org/download/

    Autoloading classes

  • Autoloading by hand
  • Autoloading through composer

  • Autoloading by hand

    Classes are arranged in namespaces relative to directories:
  • Nearsoft\SeleniumClient\ class is located at
  • src/Nearsoft/SeleniumClient/WebDriver.php
  • Nearsoft\SeleniumClient\Http\HttpClient class is located at
  • src/Nearsfot/SeleniumClient/Http/HttpClient.php

    Therefore you can define an autoloader function in your root-located bootstrap file (as in test/bootstrap.php) like
    spl_autoload_register(function($className) {
    $path = __DIR__ . "/../src/" . str_replace("\\", "/", $className) . '.php';
    if (file_exists($path)) {
    require $path;
    return true;
    }
    return false;
    });
    Require the file with the autoload function registration
    require('path/to/bootstrap.php');
    You can now make references to classes as in here
    use Nearsoft\SeleniumClient\WebDriver; use Nearsoft\SeleniumClient\By;
    $webDriver = new WebDriver();
    $webDriver->get("http://nearsoft-php-seleniumclient.herokuapp.com/sandbox/");
    $webElement = $webDriver->findElement(By::id("txt1"));
    var_dump($webElement->describe());

    //Produces
    array (size=8)
    'id' => string '0' (length=1)
    'enabled' => boolean true
    'selected' => boolean false
    'text' => string '' (length=0)
    'displayed' => boolean true
    'tagName' => string 'input' (length=5)
    'class' => string 'com.sun.proxy.$Proxy3' (length=21)
    'hCode' => int 783583921

    Autoloading through composer

    Instructions on installing and using composer at getcomposer.org and packagist.org
    Have this entry in your composer.json file:
    {
    "require": {
    "nearsoft/php-selenium-client": "2.0.*"
    }
    }

    Navigate to your project's root directory and run
    $php composer.phar install
    Loading composer repositories with package information
    Installing dependencies (including require-dev)
    - Installing nearsoft/php-selenium-client (v2.0)
    Downloading: 100%

    Writing lock file
    Generating autoload files

    Composer will generate vendor/ directory with autoload.php class in it,
    just require it:
    require 'vendor/autoload.php';

    You can now make references to classes as in here
    use Nearsoft\SeleniumClient\WebDriver;
    use Nearsoft\SeleniumClient\By;

    $webDriver = new WebDriver();
    $webDriver->get("http://nearsoft-php-seleniumclient.herokuapp.com/sandbox/");
    $webElement = $webDriver->findElement(By::id("txt1"));

    var_dump($webElement->describe());

    //Produces
    array (size=8)
    'id' => string '0' (length=1)
    'enabled' => boolean true
    'selected' => boolean false
    'text' => string '' (length=0)
    'displayed' => boolean true
    'tagName' => string 'input' (length=5)
    'class' => string 'com.sun.proxy.$Proxy3' (length=21)
    'hCode' => int 783583921

    How run demo and test

    Needed:
  • Execute Selenium Server JAR file
  • Execute demos
  • Execute test
  • Execute Selenium Server JAR file

  • On debian enviroment
  • Open up a terminal and run
    $java -jar path/selenium-server-standalone-version.jar

    For more information check this page: http://docs.oracle.com/javase/tutorial/deployment/jar/run.html

    Execute demos

    Open up another terminal, navigate to demo/ and run
    $phpunit Demo1.php
    $phpunit Demo2.php

    How open a browser and navigate

    Open a browser

    Start session and open a browser
    $desiredCapabilities = new DesiredCapabilities("firefox");
    $webDriver = new WebDriver($desiredCapabilities);

    Navigate to URL

    Navigate to the URL into the browser
    $webDriver->get("http://nearsoft.com/");

    Navigation

  • Forward
  • Navigate to the next URL in the history list.
    $webDriver->navigate()->forward();

  • Back
  • Navigate to the previous URL in the history list.
    $webDriver->navigate()->back();

  • Refresh
  • Refresh the page
    $webDriver->navigate()->refresh();

  • Get Current URL
  • $webDriver->getCurrentUrl();

    Finding elements from the DOM

    You can get a instance of WebElement which represents an element in the DOM by invoking WebDriver::findElement and passing a strategy to locate the element. These strategies are:
  • Class name
  • Css selector
  • Id
  • JsSelector
  • Name
  • Link text
  • Partial link text
  • Tag name
  • XPath

  • Find element by element's class name
    $webElement = $webDriver->findElement(By::className("class_name"));

    Find element by element's css selector path
    $webElement = $webDriver->findElement(By::cssSelector("select#sel2 option[value='tomatoes']"));

    Find element by element's id
    $webElement = $webDriver->findElement(By::id("element_id"));

    Find element by element's javascript selector
    Define a selector used by javascript by passing the selector and optionally the selector receptor definition (default is '$').
    $webElement = $webDriver->findElement(By::jsSelector("#content .red"));
    $webElement = $webDriver->findElement(By::jsSelector("#content .red", 'document.querySelectorAll'));
    $webElement = $webDriver->findElement(By::jsSelector("#content .red", 'jQuery'));

    Find element by element's name
    $webElement = $webDriver->findElement(By::name("element_name"));

    Find element by element's link text
    $webElement = $webDriver->findElement(By::linkTest("Link Text"));

    Find element by part of element's link text
    $webElement = $webDriver->findElement(By::partialLinkText("Partial Link Test"));

    Find element by element's tag name
    $webElement = $webDriver->findElement(By::tagName("p"));

    Find element by element's xPath
    $webElement = $webDriver->findElement(By::("/html/body/table/tbody/tr/td[1]/fieldset/form/p[4]"));

    Multiple elements

    WebDriver::findElement returns an instance of WebElement.

    In case multiple elements match the condition, the first matching element will be returned.

    For getting a collection of multiple WebElements use
    WebDriver::findElements which receives the same locator definition as
    WebDriver::findElement.

    Holding the flow for waiting

    You can hold the flow for elements to be present in the DOM under certain expected time.

    Wait for element with id 'element_id' to be present with timeout of 10 seconds:
    $webElement = $webDriver->waitForElementUntilIsPresent(By::id("element_id"), 10);
    $webElement = $webDriver->waitForElementUntilIsNotPresent(By::id("element_id"), 10);

    This internally uses WebDriverWait class, which you can access directly:
    $wait = new WebDriverWait(8);
    $webElement = $wait->until($webDriver,"findElement",array(By::id("element_id"),true));

    Manipulate elements

    A WebElement instance represents a DOM element and you can manipulate it through these methods
    Gets element's id
    $webElement->getElementId();

    Send text to element
    $webElement->sendKeys("text");

    Gets element's visible text
    $webElement->getText();

    Gets element's tag name
    $webElement->getTagName();

    Sets element's specified atribute's value
    $webElement->setAttribute("attribute_name","value");

    Gets element's specified attribute's value
    $webElement->getAttribute("attribute_name");

    Gets whether element is selected
    $webElement->isSelected();

    Gets whether element is displayed
    $webElement->isDisplayed();

    Gets whether element is enabled
    $webElement->isEnabled();

    Clear current element's text
    $webElement->clear();

    Click on element
    $webElement->click();

    Submit form from element
    $webElement->submit();

    Gets element's description
    $webElement->describe();

    Adds css class on element
    $webElement->addClass("class_css");

    Gets element's css class
    $webElement->hasClass();

    Removes element's css class
    $webElement->removeClass();

    Gets element's coordinates
    $webElement->getCoordinates();

    Gets element's coordinates after scrolling
    $webElement->getLocationOnScreenOnceScrolledIntoView();

    Finds elements within current element
    $webElement->findElements(By::id("id"));

    Waits for expected element to be present within current element
    $webElement->waitForElementUntilIsPresent(By::id("id"));

    Waits for current element to be displayed
    $webElement->waitForElementUntilIsDisplayed($timeOutSeconds);

    Waits for current element to be enabled
    $webElement->waitForElementUntilIsEnabled($timeOutSecond);

    Waits until current element's text has changed
    $webElement->waitForElementUntilTextIsChanged("targetText", $timeOutSecond);

    Waits until current element's text equals specified
    $webDriver->waitForElementUntilIsPresentWithSpecificText(By::id("id"),"targetText", $timeOutSecond);

    Handling windows and frames

    Handling windows

  • Get window
  • Change to the Window by passing in the name
    $webDriver->switchTo()->window("popUp1");
    OR
    $webDriver->switchToWindow('popup1');

    Handling frame

  • Get frame
  • Focus on specified frame
    $webDriver->switchTo()->frame(null);
    OR
    $webDriver->switchToFrame(null);

  • Get frame By index
  • Move to a different frame using its index
    $webDriver->switchTo()->frame(0);

  • Get frame by name
  • Move to a frame through a webElement
    $webDriver->switchTo()->frame("iframe1");

    Handling javascript alerts, confirm and prompt dialogs

    Javascript alerts, prompts, confirm dialogs

    For getting the text of the current alert, prompt or confirm dialog:
    $webDriver->switchTo()->alert()->getText();

    For clicking the 'OK' button of the dialog:
    $webDriver->switchTo()->alert()->accept();

    Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog. For dismissing the current dialog:
    $webDriver->switchTo()->alert()->dismiss();

    To sends keys to the alert
    $webDriver->switchTo()->alert()->sendKeys($string);

    Taking screenshots

    Screenshot images of the current page can be generated and stored at any convenient time.
    Once you have a WebDriver instance, set the save directory path
    $webDriver->setScreenShotsDirectory('/path/for/saving/screenshots');

    You can now take the screenshot by simply doing
    $webDriver->screenshot();

    Image will get saved in the specified directory inside a another directory with name of the SessionId. Image file name is saved in time stamped form. You can retrieve the file name by assigning the call result to a variable
    $filePath = $webDriver->screenshot();

    $filePath will provide a file name like 20131018131030000000-1.png
    That file's full path will be "/path/for/saving/screenshots/{$webDriver->getSessionId()}/{$filePath}"
    You may also override the default screenshot directory by doing
    $webDriver->screenshot('/overriding/path');

    Executing javascript

    You can execute custom javascript synchronously and asynchronously.
    Synchronously
    $webDriver->executeScript("console.log('foo');");

    Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client. The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified.

    $webDriver->executeScript("console.log(arguments);",array(1,2,3));
    // The 'arguments' object in javascript will be [1,2,3]
    // Think of this as a function being injected and invoked as:
    // var seleniumFunction = function(arguments){console.log(arguments)}; seleniumFunction([1,2,3]);

    $result = $webDriver->executeScript("return 'var';"); // $result in PHP will equal 'var'

    Asynchronously

    Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous and must signal that is done by invoking the provided callback, which is always provided as the final argument to the function. The value to this callback will be returned to the client. Asynchronous script commands may not span page loads. If an unload event is fired while waiting for a script result, an error should be returned to the client.


    The script argument defines the script to execute in the form of a function body. The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified. The final argument will always be a callback function that must be invoked to signal that the script has finished.

    $webDriver->executeAsyncScript("console.log('async'); var callbackFunction = arguments[arguments.length - 1]; callbackFunction();");
    // Even though there are no custom arguments being passed to the javascript function,
    // a callback is passed implicitly through the 'arguments' object, always being the last one.
    // This callback must be called by the async script otherwise you will get a SeleniumScriptTimeoutException

    Cookies

  • Sets cookie
  • $webDriver->manage()->setCookie("cookie_name", "value");
  • Gets current cookies
  • $webDriver->manage()->getCookies();
  • Removes cookie
  • $webDriver->manage()->deleteCookie($cookie);
    Or by Name
    $webDriver->manage()->deleteCookieNamed("cookie_name");
  • Removes all current cookies
  • $webDriver->manage()->deleteAllCookies();

    Setting timeouts

    Set the amount of time, in milliseconds, that asynchronous scripts executed are permitted to run before they are aborted.
    $timeouts = $webDriver->manage()->timeouts();
    $timeouts->setScriptTimeout(1);

    Configure the amount of time that a particular type of operation can execute for before they are aborted.
    $timeOuts = $webDriver->manage()->timeouts();
    $timeOuts->pageLoadTimeout(1);

    Setting capabilities

    You need to create a instance of DesiredCapabilities, And then assignment through the construct of webDriver.

    $desiredCapabilities = new DesiredCapabilities("firefox");
    $desiredCapabilities->setCapability(CapabilityType::javascriptEnabled,1);
    $webDriver = new WebDriver($desiredCapabilities);
    Note: when you set a capability you need to use the abstract class of CapabilityType and use a valid Capability Type :
  • browserName
  • version
  • platform
  • javascriptEnabled
  • takesScreenshot
  • takesScreenshot
  • takesScreenshot
  • locationContextEnabled
  • applicationCacheEnabled
  • browserConnectionEnabled
  • cssSelectorsEnabled
  • webStorageEnabled
  • rotatable
  • acceptSslCerts
  • nativeEvents
  • proxy