Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aczietlow/7c4834f79a7afd920d8f to your computer and use it in GitHub Desktop.
Save aczietlow/7c4834f79a7afd920d8f to your computer and use it in GitHub Desktop.
Cheat sheet for using php webdriver (facebook/webdriver).

Webdriver PHP API workthough

  • Open a browser

    # start an instance of firefox with selenium-webdriver
    $browser_type = 'firefox'
    $host = 'http://localhost:4444/wd/hub'
    $capabilities = array(\WebDriverCapabilityType::BROWSER_NAME => $browser_type);
    $driver = RemoteWebDriver::create($host, $capabilities);
    # :firefox => firefox
    # :chrome  => chrome
    # :ie      => iexplore
  • Go to a specified URL


    'NOTE' -- the WebDriver may not wait for the page to load, you'd better using explicit and implicit waits.

  • Locating Elements

    • 'findElement(WebDriverBy $by)' -- Find the first element matching the given arguments.

    • 'findElements(WebDriverBy $by)' -- Find all elements matching the given arguments

    • 'WebDriverBy' -- Class with static methods for selecting elements using different mechanisms.

      • 'WebDriverBy
        • 'class name'
        • 'css selector'
        • 'id'
        • 'name'
        • 'link text'
        • 'partial link text'
        • 'tag name'
        • 'xpath'
    • Finding Element By ID

      # example html
      # <input id="q">...</input>
      $element = $driver->findElement(WebDriverBy::id("q"));
    • By Class Name

      # example html
      # <div class="highlight-java" style="display: none; ">...</div>
      $element = $driver->findElement(WebDriverBy::className('highlight-java'));
    • By Tag Name

      # example html
      # <div class="highlight-java" style="display: none; ">...</div>
      $element = $driver->findElement(WebDriverBy::tagName("div"));
    • By Name

      # example html
      # <input id="q" name='search' type='text'>…</input>
      $element = $driver->findElement(WebDriverBy::name('search'));
    • By Link Text

      # example html
      # <a href="">cheese</a>
      $element = $driver->findElement(WebDriverBy::linkText("cheese"));
    • By Partial Link Text

      # example html
      # <a href="">search for cheese</a>
      $element = $driver->findElement(WebDriverBy::partialLinkText("chee"));
    • By XPath

      # example html
      # <ul class="dropdown-menu">
      #   <li><a href="/login/form">Login</a></li>
      #   <li><a href="/logout">Logout</a></li>
      # </ul>
      $element = $driver->findElement(WebDriverBy::xpath('//a[@href='/logout']'));
      • NOTE -- When using Element#findElement with WebDriverBy::xpath, be aware that,

        • webdriver follows standard conventions: a search prefixed with "//" will search the entire document, not just the children of this current node.
        • Use ".//" to limit your search to the children of the receiving Element.
    • By CSS Selector

        # example html
        # <div id="food">
        #   <span class="dairy">milk</span>
        #   <span class="dairy aged">cheese</span>
        # </div>
        $element = $driver->findElement(WebDriverBy::cssSelector('#food span.dairy'));
  • Element's operation

    • Button/Link/Image

      $element = $driver->findElement(WebDriverBy::id('BUTTON_ID'))->click();
    • Text Field

      # input some text
      # send keyboard actions, press `cmd+a` & `delete`
          WebDriverKeys::COMMAND, // Use control on non-mac computers.

      *'Note' -- /RemoteWebElement->clear() will clear text from a textarea or a text input.

    • Checkbox/Radio

      # check if it is selected
      # select the element
      # deselect the element
    • Select

      # get the select element	
      $select = $driver->findElement(WebDriverBy::tagName('select'));
      # get all the options for this element
      $allOptions = $select->findElement(WebDriverBy::tagName('option'));
      # select the options
      foreach ($allOptions as $option) {
        echo "Value is:" . $option->getAttribute('value);
    • visibility

    • get text

    • get attribute

  • Driver's operation

    • execute javascript

        $driver->executeScript("return window.location.pathname");
    • wait for a specific element to show up

        # set the timeout to 20 seconds, and the time in interval to 1000 ms
        $driver->wait(20, 1000)->until(
            WebDriverExpectedCondition::titleIs('WebDriver Page')
    • implicit waits

    An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available

    	# set the timeout for implicit waits as 10 seconds
    	$driver->manage()->timeouts()->implicitlyWait = 10
    	$element = $driver->findElement(WebDriverBy::id('some-dynamic-element'));
    • switch between frames

        # switch to an iframe
        $driver->switchTo()->frame(/WebDriverElement('the id or the name of the frame"some-frame" # name or id'));
        # switch back to the main document
    • swich between windows

        #TODO: Add examples.
    • handle javascript dialog

        # get the alert
        $a = $driver->switchTo->alert();
        # operation on the alert
        if ($a->getText == 'A value you are looking for') {
        else {
  • Cookies

    • Delete cookies

        # You can delete cookies in 2 ways
        # By name
        # Or all of them
Copy link

Why not close the old unused windows after your tests?

Copy link

Sarana-Anna commented Jan 11, 2017

Why not close the old unused windows after your tests?

public function tearDown()

Copy link

How to set a cookie?

Copy link

how to move to new tab?

Copy link


Copy link

It's worth mentioning $driver->navigate()->back(); to go back as well as $driver->navigate()->refresh(); to refresh the current page.

Copy link

Thanks a lot

Copy link

tdhouibi commented Sep 18, 2017

Hi aczieltlow , and every Body
do you have an Idea how can i add Torifier this Browser Tor to the phpCode:
// start Firefox with 5 second timeout
$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::firefox();
$driver = RemoteWebDriver::create($host, $capabilities, 5000);


Copy link

Very Helpful

Copy link

Missing '

echo "Value is:" . $option->getAttribute('value);
echo "Value is:" . $option->getAttribute('value');

Copy link

Select option by value

$driver->findElement(WebDriverBy::cssSelector('select[name="_________"] option[value="____________"]'))->click();

Copy link

Fullscreen mode:


Copy link

Great gist!! Thank you sir

Copy link

Great gist. A little correction though, for select with value it should be:

# get the select element	
$select = $driver->findElement(WebDriverBy::tagName('select'));

Copy link

Tell me what the error is. These are two identical codes. But for some reason I can not assign data to $basic_list.

private function driverWait($identification, $element, $count = 0) {
            function () use ($identification, $element, $count) {
                $elements = $this->driver->findElements(WebDriverBy::$identification($element));
                echo "Wait | [{$element}] count: ".count($elements)."\n";
                return count($elements) > $count;

deepinscreenshot_ - _20180425173802

Copy link

I did it differently. I passed the html page to DomCrawler and there I pulled out the necessary data.

Copy link

How to do assertion here like asserttrue, Assertequals etc

Copy link

ildarius commented May 9, 2019

To get the whole HTML content of a given element do getAttribute->('innerHTML').


Copy link

ildarius commented May 9, 2019

To get contents of an element generated by javascript, you would wait for your target to load using

$driver->wait(10, 1000)->until(

and then scrape everything inside that class using:

$content = $driver->findElement(WebDriverBy::className("CLASS_NAME"))->getAttribute('innerHTML');

Copy link

kaiserwaseem commented May 9, 2019

//To get the session id of your script
$sessionId = $driver->getSessionID();

//To use the same browser session each time i run my script :
$driver = RemoteWebDriver::createBySessionID($sessionId);

//To get all available sessions
$sessionsArray = $driver->getAllSessions();

Copy link

//close child browser window and move back to parent browser window

$browser_windows = $webdriver->getWindowHandles();

$browser_windows = $webdriver->getWindowHandles();

Copy link

Awesome explanation.

Copy link

How to handle a file dialog (like used on upload forms)?

Copy link

pauloacosta commented Feb 25, 2021

Scroll a Window to the end:

$actualHeight = 0;
$nextHeight = 0;
while (true) {
    try {
        $nextHeight += 20;      
        $actualHeight =  $driver->executeScript('return document.body.scrollHeight;');
        if ($nextHeight >= ($actualHeight - 50 ) ) break;
        $driver->executeScript("window.scrollTo(0, $nextHeight);");
        $driver->manage()->timeouts()->implicitlyWait = 5;
    } catch (Exception $e) {

Copy link

Check if a element was found:

if (count($drive->findElements(WebDriverBy::cssSelector('video'))) > 0) {
$videoURL = $drive->findElement(WebDriverBy::cssSelector('video'))->getAttribute('src');
} else {
echo "Element not found!";

if you use "findElement" instead of "findElements" and the element cannot be found, php will throw a exception.

Copy link

listing multiple elements found:

if (count($drive->findElements(WebDriverBy::cssSelector('a'))) != 0){
    $links = $drive->findElements(WebDriverBy::cssSelector('a'));
    foreach ($links as $key => $value) {
        echo $value->getAttribute('href');

Copy link

/* Working with Tabs */


// Get first window hWND
$lstr_window1 = $lobj_Driver->getWindowHandle();

// Open second tab and get the hWND from second tab
$lstr_window2 = $lobj_Driver->getWindowHandle();

// alternate to 1st window

// alternate to 2nd window

Copy link

Copy link

How to handle a file dialog (like used on upload forms)?

hello, did you manage to handle it?

Copy link

How to handle a file dialog (like used on upload forms)?

hello, did you manage to handle it?

I just set the value of the field that the dialog stores the file:


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment