企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> 用浏览器驱动的方式,很方便我们在测试阶段调试代码正确性,但是由于浏览器要启动,解析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); } ?> ~~~