QueryList与PhantomJS集成概述
QueryList采用类似jQuery的语法进行数据抓取,并具备丰富的扩展插件功能。下文将展示如何借助PhantomJS插件,实现对由JavaScript动态生成的页面内容进行抓取。
安装依赖与下载二进制文件
一、环境安装
推荐使用Composer工具进行依赖管理:
1. 部署QueryList核心库
composer require jaeger/querylist
GitHub: https://github.com/jae-jae/QueryList
2. 部署PhantomJS扩展插件
composer require jaeger/querylist-phantomjs
GitHub: https://github.com/jae-jae/QueryList-PhantomJS
二、获取PhantomJS执行文件
访问PhantomJS官网 http://phantomjs.org ,根据操作系统平台下载对应的二进制可执行文件。
三、插件API说明
QueryList::browser($url, $debug = false, $commandOpt = []): 该方法用于启动浏览器引擎以打开指定URL连接。
动态页面采集实战示例
四、实战应用
以采集「今日头条」手机版为例,该站点基于React框架构建,其页面内容完全由动态脚本渲染生成。
以下代码演示QueryList中PhantomJs插件的具体调用方式:
1. 初始化插件实例
use QL\QueryList;
use QL\Ext\PhantomJs;
$ql = QueryList::getInstance();
// 安装时需要设置PhantomJS二进制文件路径
$ql->use(PhantomJs::class,'/usr/local/bin/phantomjs');
//or Custom function name
$ql->use(PhantomJs::class,'/usr/local/bin/phantomjs','browser');
2. 示例代码-1
首先获取经过JS渲染后的完整HTML源码:
$html = $ql->browser('https://m.toutiao.com')->getHtml();
print_r($html);
接着提取页面中所有<p>标签内的文本信息:
$data = $ql->browser('https://m.toutiao.com')->find('p')->texts();
print_r($data->all());
运行结果如下:
Array(
[0] => 自拍模式开启!国庆假期我和国旗合个影
[1] => 你旅途已开始 他们仍在自己的岗位上为你的假期保驾护航
[2] => 喜极而泣,都教授终于回到地球了! //....)
若需配置HTTP代理服务器:
// 更多选项可以查看文档:
http://phantomjs.org/api/command-line.html
$ql->browser('https://m.toutiao.com',true,[
// 使用http代理
'--proxy' => '192.168.1.42:8080', '--proxy-type' => 'http'
])
3. 示例代码-2
构建一个更复杂的自定义请求逻辑:
$data = $ql->browser(function (\JonnyW\PhantomJs\Http\RequestInterface $r){
$r->setMethod('GET');
$r->setUrl('https://m.toutiao.com');
$r->setTimeout(10000); // 10 seconds
$r->setDelay(3); // 3 seconds
return $r;
})->find('p')->texts();
print_r($data->all());
开启调试模式,并从指定路径加载本地Cookie文件:
$data = $ql->browser(function (\JonnyW\PhantomJs\Http\RequestInterface $r){
$r->setMethod('GET');
$r->setUrl('https://m.toutiao.com');
$r->setTimeout(10000); // 10 seconds
$r->setDelay(3); // 3 seconds
return $r;
},true,[
'--cookies-file' => '/path/to/cookies.txt'
])->rules([
'title' => ['p','text'],
'link' => ['a','href']
])->query()->getData();
print_r($data->all());