Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ildarius/899330fc3579da39d0f6da5068a523e5 to your computer and use it in GitHub Desktop.
Save ildarius/899330fc3579da39d0f6da5068a523e5 to your computer and use it in GitHub Desktop.
PHP selenium webdriver CheatSheet (facebook/webdriver).
@ildarius
Copy link
Author

ildarius commented Aug 22, 2020

Open a browser and go to a URL

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

Find an element with the id named cool_id

<input id="cool_id">...</input>

$element = $driver->findElement(WebDriverBy::id("cool_id"));

By Class Name

Find an element whose with a class name of 'highlight-java

<div class="highlight-java" style="display: none; ">...</div>

$element = $driver->findElement(WebDriverBy::className('highlight-java'));

By Tag Name

Find an element whose with a DIV tag:

<div class="highlight-java" style="display: none; ">...</div>

$element = $driver->findElement(WebDriverBy::tagName("div"));

By Name

Find an element with the name 'search':

<input id="q" name='search' type='text'>…</input>

$element = $driver->findElement(WebDriverBy::name('search'));

By Link Text

Find an element with the anchor text that says 'cheese':

<a href="http://www.google.com/search?q=cheese">cheese</a>

$element = $driver->findElement(WebDriverBy::linkText("cheese"));

By Partial Link Text

Find an element whose anchor text contains 'chee'

<a href="http://www.google.com/search?q=cheese">search for cheese</a>

$element = $driver->findElement(WebDriverBy::partialLinkText("chee"));

By XPath

Find an element whose a href value equals to logout

  <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']'));

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
Find an element that's inside a div ID called food whose span class equals to dairy:

   <div id="food">
     <span class="dairy">milk</span>
     <span class="dairy aged">cheese</span>
   </div>

$element = $driver->findElement(WebDriverBy::cssSelector('#food span.dairy'));

Interacting with elements

Click Button/Link/Image

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

Click with JS

        $wait = new WebDriverWait($this->d, 30);
        $wait->until(WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::id('SOME_ID')));

        if($btn = $this->d->findElement(WebDriverBy::id('SOME_ID'))) {
            if($this->d->executeScript("arguments[0].click();", [$btn]));
        }

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 (Click a specific option "727" inside a select element with ID Fm112_Ctrl3227_LB)

$dropdown   = $driver->findElement(WebDriverBy::id('Fm112_Ctrl3227_LB'));
$allOptions = $dropdown->findElements(WebDriverBy::tagName('option'));

foreach ($allOptions as $option) {

    if($option->getAttribute('value') == "727") {
	$option->click();
    }

}

Select a dropdown action (alternative approach if something's not working, like if other options remain selected when they shouldn't be)

Combine WebDriverSelect::selectByValue with clickAndHold). Following shows how to do it with a dropdown with an ID Fm112_Ctrl3227_LB and option value 727:

// Look for the select dropdown with ID Fm112_Ctrl3227_LB and click and hold the option with the value 727
$dropdown   = $driver->findElement(WebDriverBy::id('Fm112_Ctrl3227_LB'));
$allOptions = $dropdown->findElements(WebDriverBy::tagName('option'));

foreach ($allOptions as $option) {

    if($option->getAttribute('value') == "727") {

	$driver->action()
	    ->moveToElement($option)
	    ->clickAndHold($option)
	    ->perform();

    }

}

Alternative select a dropdown option

$select = new WebDriverSelect($driver->findElement(WebDriverBy::id('ID')));
$select->selectByValue('VAL');

Driver's operation

Execute javascript

$driver->executeScript("return window.location.pathname");

Wait explicit

Wait for a specific element to show up (element has to be in DOM)
Wait until we see the title of the page being 'WebDriver Page' (may not work if element is not in DOM)

// Set the timeout to 20 seconds, and the time in interval to 1000 ms
$driver->wait(20, 1000)->until(
    WebDriverExpectedCondition::titleIs('WebDriver Page')
);

Wait for a specific element to show up (element may be added by Javascript)

Wait for the select option with the value of 100 to appear:

$wait = new WebDriverWait($this->driver, 30);	
$wait->until(WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::xpath('//select/option[@value="100"]')));

NOTE: Sometimes the browser may not be seeing it when it checks visibilityOfElementLocated in that case it may be better to use presenceOfElementLocated, which makes sure that the element is there but not necessarily visible.

Wait for an attribute to show up on the page

For example an attribute/tag like data-lat="45.52341417"

$wait = new WebDriverWait($this->driver, 30);	
$wait->until(WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::xpath('//*[@data-lat]')));

Wait until Ajax stops working, for example if it's loading new containers

$wait = new WebDriverWait($driver, 30);
$wait->until(
    function ($driver) {
        return $driver->executeScript('return jQuery.active === 1
        ;');
    }
);

src

Wait implicit

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'));

More details here https://github.com/php-webdriver/php-webdriver/wiki/HowTo-Wait

Switch between frames and windows

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();

Switch between windows

$handles = $driver->getWindowHandles();
$driver->switchTo()->window(end($handles));

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 by name

$driver->manage()->deleteCookieNamed('CookieName');

Delete all cookies

$driver->manage()->deleteAllCookies();

Get page source

$driver->getPageSource();

Check visibility and fetch values

See if an element with ID 'element' is visible

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

Get text value

Get text displayed inside a div id named 'element:
$driver->findElement(WebDriverBy::id('element'))->getText();

Get attribute

What are the attributes (like CSS) of a div ID named 'element':
$driver->findElement(WebDriverBy::id('element'))->getAttribute('class');

Errors

WebDriverSelect error (PHP Fatal error: Uncaught Error: Class 'Facebook\WebDriver\WebDriver\WebDriverSelect' not found)

Make sure namespace is used as in:
use Facebook\WebDriver\WebDriverSelect;

You can then run commands like:
$dropdown = new WebDriverSelect($driver->findElement(WebDriverBy::id('Fm112_Ctrl3227_LB')));

When fetching the page values the non-ascii characters come out with messed up encoding

If you're fetching the contents of DOM with something like DOMDocument make sure to pass the correct encoding like below

$doc = new \DOMDocument();
$doc->loadHTML(mb_convert_encoding($this->markup, 'HTML-ENTITIES', 'UTF-8'));

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