php使用ChromeDriver控制浏览器
先查看Chrome浏览器的版本:浏览器菜单:帮助->关于
下载对应版本的chromedriver:
http://npm.taobao.org/mirrors/chromedriver/
http://chromedriver.storage.googleapis.com/index.html
两个地址都可以下。
下载完后解压出:chromedriver.exe
命令行运行:
chromedriver.exe
命令会启动默认端口是9515的一个web服务。(http://locahost:9515 可以访问到说明成功)
用PHP控制浏览器:
PHP-webdriver 库是 Selenium WebDriver 的 PHP 语言绑定,它允许您从 PHP 控制 Web 浏览器。
首先下载php-webdriver包:
composer require php-webdriver/webdriver
github项目地址:https://github.com/php-webdriver/php-webdriver
说明文档:https://github.com/php-webdriver/php-webdriver/wiki/Example-command-reference然后编写PHP示例代码:
<?php
namespace Facebook\WebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
require_once('vendor/autoload.php');
$host = 'http://localhost:9515'; // 对应exe 窗口中的 端口号
$capabilities = DesiredCapabilities::chrome();
$driver = RemoteWebDriver::create($host, $capabilities, 5000);
$driver->get('https://www.baidu.com'); //自动打开的网页地址
$cookies = $driver->manage()->getCookies(); // 获取网站的cookies
// 搜索
$driver->findElement(WebDriverBy::id('kw'))
->sendKeys('PHP')
->submit();
echo $driver->getTitle(); //获取页面title
echo $driver->getCurrentURL();// 获取当前url
// 获取HTML
$html = $driver->findElement(WebDriverBy::tagName('html'))->getDomProperty('outerHTML');
echo $html;
//$driver->quit(); // 关闭浏览器