Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
    
    $browser_type
    # :firefox => firefox
    # :chrome  => chrome
    # :ie      => iexplore
    
  • Go to a specified URL

    $driver->get('http://google.com');
    $driver->navigate()->to('http://google.com');
    

    '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="http://www.google.com/search?q=cheese">cheese</a>
      
      $element = $driver->findElement(WebDriverBy::linkText("cheese"));
      
    • By Partial Link Text

      # example html
      # <a href="http://www.google.com/search?q=cheese">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
      $driver->findElement(WebDriverBy::id('BUTTON_ID'))->click();
      $driver->getKeyboard()->sendKeys('InputText');
      
      # send keyboard actions, press `cmd+a` & `delete`
      $driver->getKeyboard()
        ->sendKeys(array(
          WebDriverKeys::COMMAND, // Use control on non-mac computers.
          'a',
        ));
      
      $driver->getKeyboard()
        ->sendKeys(array(
          WebDriverKeys::BACKSPACE,
        ));
      

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

    • Checkbox/Radio

      # check if it is selected
      $driver->findElement(WebDriverBy::id('CheckBox'))->isSelected();
      
      # select the element
      $driver->findElement(WebDriverBy::id('CheckBox'))->click();
      
      # deselect the element
      $driver->findElement(WebDriverBy::id('CheckBox'))->clears();
      
    • 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);
        $option->click();
      }
      
    • visibility

      $driver->findElement(WebDriverBy::id('element'))->isDisplayed();
      
    • get text

      $driver->findElement(WebDriverBy::id('element'))->getText();
      
    • get attribute

      $driver->findElement(WebDriverBy::id('element'))->getAttribute('class');
      
  • 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
    	
    	$driver->get("http://somedomain/url_that_delays_loading");
    	$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
        $driver->switchTo()->defaultContent();
      
    • 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') {
          a->dismiss();
        }
        else {
          a->accept();
        }
      
  • Cookies

    • Delete cookies

        # You can delete cookies in 2 ways
        # By name
        $driver->manage()->deleteCookieNamed('CookieName');
      
        # Or all of them
        $driver->manage()->deleteAllCookies();
      
@m-abdulsamad-confiz

This comment has been minimized.

Show comment
Hide comment
@m-abdulsamad-confiz

m-abdulsamad-confiz commented Dec 2, 2015

(Y)

@emiglobetrotting

This comment has been minimized.

Show comment
Hide comment
@emiglobetrotting

emiglobetrotting commented Jan 18, 2016

thanks.

@Arapi-Alena

This comment has been minimized.

Show comment
Hide comment
@Arapi-Alena

Arapi-Alena commented Jan 18, 2016

thx

@mattboothman

This comment has been minimized.

Show comment
Hide comment
@mattboothman

mattboothman Jan 28, 2016

Awesome stuff, ta

mattboothman commented Jan 28, 2016

Awesome stuff, ta

@fluid217

This comment has been minimized.

Show comment
Hide comment
@fluid217

fluid217 Mar 7, 2016

Really helpful, Thanks!

There is one error though:
$allOptions = $select->findElement(WebDriverBy::tagName('option'));

should read:
$allOptions = $select->findElements(WebDriverBy::tagName('option'));
(notice the plural of Elements)

fluid217 commented Mar 7, 2016

Really helpful, Thanks!

There is one error though:
$allOptions = $select->findElement(WebDriverBy::tagName('option'));

should read:
$allOptions = $select->findElements(WebDriverBy::tagName('option'));
(notice the plural of Elements)

@timokern

This comment has been minimized.

Show comment
Hide comment
@timokern

timokern Mar 10, 2016

This helps me a lot, thanks mate!

timokern commented Mar 10, 2016

This helps me a lot, thanks mate!

@oleksandr-butenko

This comment has been minimized.

Show comment
Hide comment
@oleksandr-butenko

oleksandr-butenko Mar 16, 2016

Thanks! It was useful

oleksandr-butenko commented Mar 16, 2016

Thanks! It was useful

@georgii-sirotkin

This comment has been minimized.

Show comment
Hide comment
@georgii-sirotkin

georgii-sirotkin May 29, 2016

There's an error.
$driver->manage()->timeouts()->implicitlyWait = 10
should be
$driver->manage()->timeouts()->implicitlyWait(10)
implicitlyWait is a method.

Thanks for great work btw)

georgii-sirotkin commented May 29, 2016

There's an error.
$driver->manage()->timeouts()->implicitlyWait = 10
should be
$driver->manage()->timeouts()->implicitlyWait(10)
implicitlyWait is a method.

Thanks for great work btw)

@JeanGazaniol

This comment has been minimized.

Show comment
Hide comment
@JeanGazaniol

JeanGazaniol Jun 10, 2016

Thanks for the great work yeah !

JeanGazaniol commented Jun 10, 2016

Thanks for the great work yeah !

@kbcmdba

This comment has been minimized.

Show comment
Hide comment
@kbcmdba

kbcmdba Sep 18, 2016

The following line is missing a tick mark...

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

Note 'value should be 'value'

kbcmdba commented Sep 18, 2016

The following line is missing a tick mark...

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

Note 'value should be 'value'

@jihadismail8

This comment has been minimized.

Show comment
Hide comment
@jihadismail8

jihadismail8 Dec 2, 2016

how to use the same browser session each time i run my script ??? because each time i test my script it opens a new windows which takes alot of resources ... any help guys ?

jihadismail8 commented Dec 2, 2016

how to use the same browser session each time i run my script ??? because each time i test my script it opens a new windows which takes alot of resources ... any help guys ?

@cryptton2004

This comment has been minimized.

Show comment
Hide comment
@cryptton2004

cryptton2004 Dec 6, 2016

Why not close the old unused windows after your tests?

cryptton2004 commented Dec 6, 2016

Why not close the old unused windows after your tests?

@Sarana-Anna

This comment has been minimized.

Show comment
Hide comment
@Sarana-Anna

Sarana-Anna Jan 11, 2017

Why not close the old unused windows after your tests?

public function tearDown()
{
$this->webDriver->quit();
}

Sarana-Anna commented Jan 11, 2017

Why not close the old unused windows after your tests?

public function tearDown()
{
$this->webDriver->quit();
}

@Eddcapone

This comment has been minimized.

Show comment
Hide comment
@Eddcapone

Eddcapone Feb 14, 2017

How to set a cookie?

Eddcapone commented Feb 14, 2017

How to set a cookie?

@gohelkiran30

This comment has been minimized.

Show comment
Hide comment
@gohelkiran30

gohelkiran30 Mar 10, 2017

how to move to new tab?

gohelkiran30 commented Mar 10, 2017

how to move to new tab?

@Vilisag

This comment has been minimized.

Show comment
Hide comment
@Vilisag

Vilisag commented May 19, 2017

Thanks!

@junkystu

This comment has been minimized.

Show comment
Hide comment
@junkystu

junkystu Jun 13, 2017

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

junkystu commented Jun 13, 2017

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

@sudheeshms

This comment has been minimized.

Show comment
Hide comment
@sudheeshms

sudheeshms Jul 6, 2017

Thanks a lot

sudheeshms commented Jul 6, 2017

Thanks a lot

@tdhouibi

This comment has been minimized.

Show comment
Hide comment
@tdhouibi

tdhouibi Sep 18, 2017

Hi aczieltlow , and every Body
do you have an Idea how can i add Torifier http://www.torifier.com/ 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);
$driver->get('https://www.example.com')

thankyou
Tarek

tdhouibi commented Sep 18, 2017

Hi aczieltlow , and every Body
do you have an Idea how can i add Torifier http://www.torifier.com/ 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);
$driver->get('https://www.example.com')

thankyou
Tarek

@selvesandev

This comment has been minimized.

Show comment
Hide comment
@selvesandev

selvesandev Oct 13, 2017

Very Helpful

selvesandev commented Oct 13, 2017

Very Helpful

@chungnt92

This comment has been minimized.

Show comment
Hide comment
@chungnt92

chungnt92 Nov 14, 2017

Missing '

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

chungnt92 commented Nov 14, 2017

Missing '

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

This comment has been minimized.

Show comment
Hide comment
@chungnt92

chungnt92 Nov 15, 2017

Select option by value

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

chungnt92 commented Nov 15, 2017

Select option by value

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

This comment has been minimized.

Show comment
Hide comment
@chungnt92

chungnt92 Nov 15, 2017

Fullscreen mode:

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

chungnt92 commented Nov 15, 2017

Fullscreen mode:

$driver->manage()->window()->maximize();
@mycarrysun

This comment has been minimized.

Show comment
Hide comment
@mycarrysun

mycarrysun Feb 26, 2018

Great gist!! Thank you sir

mycarrysun commented Feb 26, 2018

Great gist!! Thank you sir

@MibuSawatori

This comment has been minimized.

Show comment
Hide comment
@MibuSawatori

MibuSawatori Mar 7, 2018

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

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

MibuSawatori commented Mar 7, 2018

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

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

This comment has been minimized.

Show comment
Hide comment
@DmitrySkibitsky

DmitrySkibitsky Apr 25, 2018

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) {
        $this->driver->wait()->until(
            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

DmitrySkibitsky commented Apr 25, 2018

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) {
        $this->driver->wait()->until(
            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

@DmitrySkibitsky

This comment has been minimized.

Show comment
Hide comment
@DmitrySkibitsky

DmitrySkibitsky Apr 25, 2018

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

DmitrySkibitsky commented Apr 25, 2018

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

@ganthimani

This comment has been minimized.

Show comment
Hide comment
@ganthimani

ganthimani Jun 21, 2018

How to do assertion here like asserttrue, Assertequals etc

ganthimani commented Jun 21, 2018

How to do assertion here like asserttrue, Assertequals etc

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