CheatSheet for Selenium with PHP
2 min readJul 3, 2023
Here’s a cheatsheet for Selenium with PHP using the Facebook WebDriver library (php-webdriver):
// Installation:
// Install the Facebook WebDriver library using Composer
composer require facebook/webdriver
// Import the necessary classes
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
// WebDriver setup:
// Set the URL of the Selenium server
$host = 'http://localhost:4444/wd/hub';
// Set desired capabilities for the browser (e.g., Chrome)
$capabilities = DesiredCapabilities::chrome();
// Create a new RemoteWebDriver instance
$driver = RemoteWebDriver::create($host, $capabilities);
// Navigate to a URL
$driver->get('https://www.example.com');
// Find element by ID
$elementById = $driver->findElement(WebDriverBy::id('elementId'));
// Find element by name
$elementByName = $driver->findElement(WebDriverBy::name('elementName'));
// Find element by XPath
$elementByXPath = $driver->findElement(WebDriverBy::xpath('//xpath-expression'));
// Type text into an input field
$elementById->sendKeys('text to type');
// Click on an element
$elementByXPath->click();
// Get the text of an element
$text = $elementByName->getText();
echo $text;
// Get the attribute value of an element
$attributeValue = $elementById->getAttribute('attributeName');
echo $attributeValue;
// Wait for an element to be visible
$driver->wait(10)->until(
WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::id('elementId'))
);
// Execute JavaScript
$driver->executeScript('alert("Hello, Selenium with PHP!");');
// Capture a screenshot
$driver->takeScreenshot('path/to/save/screenshot.png');
// Close the current window
$driver->close();
// Quit the driver and close the session
$driver->quit();v
This is just a basic cheatsheet to get you started with Selenium using PHP. The Facebook WebDriver library provides many more features and commands for advanced web testing scenarios. Make sure to refer to the official documentation for more detailed information and examples: https://github.com/facebook/php-webdriver
For more articles consider making a follow on my account. Thanks…