Установка facebook/webdriver
curl -sS https://getcomposer.org/installer | php
php composer.phar require facebook/webdriver
Скачиваем ChromeDriver
https://sites.google.com/a/chromium.org/chromedriver/
Доступны версии под windows, linux, mac: ссылка для версии 2.29
Документация:
https://sites.google.com/a/chromium.org/chromedriver/getting-started
https://sites.google.com/a/chromium.org/chromedriver/capabilities
Запускаем ChromeDriver (chromedriver.exe)
ChromeDriver запустится на 9515 порту.
Пример инициализации драйвера:
$wd_host = 'http://localhost:9515';
$desired_capabilities = DesiredCapabilities::phantomjs();
$desired_capabilities->setCapability('acceptSslCerts', false);
$chromeOptions = new ChromeOptions();
$arguments = ["--user-agent=Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"];
$chromeOptions->addArguments($arguments);
$chromeOptions->addExtensions(['Selenium/Block-image_v1.1.crx']);
$desired_capabilities->setCapability(ChromeOptions::CAPABILITY, $chromeOptions);
$driver = RemoteWebDriver::create($wd_host, $desired_capabilities, 5000, 30000);
где мы подменяем user-agent, и добавляем в браузер заранее скачанное расширение Block-image, блокирующее показ изображений.
Скачать хром расширение можно здесь: http://chrome-extension-downloader.com.
Так же можно запускать ChromeDriver через скрипт facebook/webdriver без отдельного запуска chromedriver.exe.
putenv("webdriver.chrome.driver=/path/to/chromedriver.exe");
$driver = ChromeDriver::start($desired_capabilitie);
Файл index.php
<?php
namespace Facebook\\WebDriver;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Exception\NoSuchElementException;
use Facebook\WebDriver\Exception\WebDriverException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\Chrome\ChromeDriver;
// add
// Подключаем автолоадер классов
require_once('vendor/autoload.php');
$wd_host = 'http://localhost:9515';
$desired_capabilities = DesiredCapabilities::phantomjs();
$desired_capabilities->setCapability('acceptSslCerts', false);
$chromeOptions = new ChromeOptions();
$arguments = ["--user-agent=Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"];
$chromeOptions->addArguments($arguments);
$chromeOptions->addExtensions(['Block-image_v1.1.crx']);
$desired_capabilities->setCapability(ChromeOptions::CAPABILITY, $chromeOptions);
$driver = RemoteWebDriver::create($wd_host, $desired_capabilities, 5000, 30000);
// `['id' => 'foo']` matches `<div id="foo">`
// `['name' => 'foo']` matches `<div name="foo">`
// `['css' => 'input[type=input][value=foo]']` matches `<input type="input" value="foo">`
// `['xpath' => "//input[@type='submit'][contains(@value, 'foo')]"]` matches `<input type="submit" value="foobar">`
// `['link' => 'Click here']` matches `<a href="google.com">Click here</a>`
// `['class' => 'foo']` matches `<div class="foo">`
try {
$driver->get('https://www.google.ru');
// Ожидаем появление элемента input 30 секунд. Если не нашли - исключение в вышестоящий try
$driver->wait(30, 250)->until(
WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::cssSelector(''input.gsfi'))
);
$driver->findElement(WebDriverBy::cssSelector('input.gsfi'))->sendKeys("test");
// Проверяем доступность элемента
if (!isElementPresent($driver, WebDriverBy::cssSelector("button.sbico-c"))) {
echo "button NOT FOUND!!!";
exit;
}
// <button class="sbico-c" value="Поиск" aria-label="Поиск в Google" id="_fZl" name="btnG" type="submit">
$driver->findElement(WebDriverBy::cssSelector('button.sbico-c'))->click();
sleep(2);
// Закрываем окно браузера
#$driver->close();
$driver->quit();
} catch (WebDriverException $ex) {
echo_time();
$msg = $ex->getMessage();
echo "_Exception || msg=[[\n$msg\n]]";
}
//===============================================================
// Проверка на доступность элемента
// Возвращает true, если элемент доступен. Иначе false
function isElementPresent(&$driver, $WebDriverBy)
{
try {
$driver->manage()->timeouts()->implicitlyWait(0);
$element = $driver->findElement($WebDriverBy);
if ($element->isDisplayed()) {
return true;
} else {
return false;
}
} catch (WebDriverException $ex) {
$msg = $ex->getMessage();
if (preg_match("#Unable to locate element#is", $msg)) {
#echo "Notice | __isElementPresent || Element not found | " . $WebDriverBy;
} else {
echo "Notice | isElementPresent || Exception || [\n $msg \n]\n";
}
return false;
} finally {
$driver->manage()->timeouts()->implicitlyWait(30);
}
} // isElementPresent
http://www.seleniumhq.org/download/
https://github.com/facebook/php-webdriver
https://github.com/facebook/php-webdriver/wiki/HowTo-Wait