> 用瀏覽器驅動的方式,很方便我們在測試階段調試代碼正確性,但是由于瀏覽器要啟動,解析DOM、JS、下載圖片等,使得程序跑起來的效率并不高,這個時候我們就需要用到Phantomjs,以后臺的形式運行程序,大大的提升運行的性能。
#### 1.安裝Phantomjs
> 到http://phantomjs.org/download.html 上面去下載對應的版本,我這里下載的是windows版本的。將解壓包中的phantomjs.exe放到PHP程序根目錄,或將該exe加入到本機的環境變量中都行。
#### 2.使用Phantomjs
> 拿的是“驗證碼識別”那篇文章的代碼,只改了一處,$capabilities = DesiredCapabilities::phantomjs();這一行。
> 運行后,可以看到“驗證碼識別”程序不再啟動chrome瀏覽器,而是后臺執行,速度也快了很多。程序順利跑出了我們想要的結果~ 大家可以休息一下咯~
~~~
<?php
namespace Facebook\WebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
require_once('vendor/autoload.php');
header("Content-Type: text/html; charset=UTF-8");
const vcodeDst = 'f://vcode.png'; //驗證碼存放地址
// start Firefox with 5 second timeout
$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::phantomjs();
$driver = RemoteWebDriver::create($host, $capabilities, 5000);
$driver->get('http://www.yimuhe.com/');
$driver->manage()->window()->maximize(); //將瀏覽器最大化
$driver->takeScreenshot(vcodeDst); //截取當前網頁,該網頁有我們需要的驗證碼
$element = $driver->findElement(WebDriverBy::id('vcode_img'));
generateVcodeIMG($element->getLocation(), $element->getSize(),vcodeDst);
echo 'done!';
//關閉瀏覽器
$driver->quit();
/**
* 生成驗證碼圖片
* @param $location 驗證碼x,y軸坐標
* @param $size 驗證碼的長寬
*/
function generateVcodeIMG($location,$size,$src_img){
$width = $size->getWidth();
$height = $size->getHeight();
$x = $location->getX();
$y = $location->getY();
$src = imagecreatefrompng($src_img);
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,$x,$y,$width,$height,$width,$height);
imagejpeg($dst,$src_img);
chmod($src_img,0777);
imagedestroy($src);
imagedestroy($dst);
}
?>
~~~