原创

php使用phantomjs

安装

wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
tar xvf phantomjs-2.1.1-linux-x86_64.tar.bz2
cp phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin

测试

phantomjs hello.js

 

PHP调用phantomjs

sdk: http://jonnnnyw.github.io/php-phantomjs/4.0/

安装sdk
composer require "jonnyw/php-phantomjs:4.*"

define('VENDOR', __DIR__ . '/../../../vendor');
$loader = include VENDOR . '/autoload.php';
$client = Client::getInstance();
//这一步非常重要,务必跟服务器的phantomjs文件路径一致
$client->getEngine()->setPath('/usr/local/bin/phantomjs');
$client->isLazy(); // 让客户端等待所有资源加载完毕
$request  = $client->getMessageFactory()->createRequest();
$request->setTimeout(5000); // 设置超时时间(超过这个时间停止加载并渲染输出画面)
$response = $client->getMessageFactory()->createResponse();
//设置请求方法
$request->setMethod('GET');
//设置请求连接
$request->setUrl($link);
//发送请求获取响应
$client->send($request, $response);
if($response->getStatus() === 200) {
    //输出抓取内容
    echo $response->getContent();
    //获取内容后的处理
}
正文到此结束
本文目录