PHP 使用 QueryList 轻松采集 JavaScript 动态渲染页面
QueryList使用jQuery的方式来做采集,拥有丰富的插件。
下面来演示QueryList
使用PhantomJS
插件抓取JS动态创建的页面内容。
安装
使用Composer安装:
- 安装QueryList
composer require jaeger/querylist
- 安装PhantomJS插件
composer require jaeger/querylist-phantomjs
下载PhantomJS二进制文件
PhantomJS官网:http://phantomjs.org ,下载对应平台的PhantomJS二进制文件。
插件API
- QueryList browser($url,$debug = false,$commandOpt = []):使用浏览器打开连接
使用
以采集「今日头条」手机版为例,「今日头条」手机版基于React框架,内容是纯动态渲染出来的。
下面演示QueryList
的PhantomJs插件用法:
- 安装插件
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');
- Example-1
获取动态渲染的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'
])
- Example-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());
开启debug模式,并从本地加载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());
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由 Summer
于 7年前 加精
我喜欢querylist,用了很多次了。抓了好多小姐姐和表情包
这个插件很棒?
还支持 PhantomJs 赞
文件 vendor\jonnyw\php-phantomjs\src\JonnyW\PhantomJs\DependencyInjection\ServiceContainer.php 报错
@lovecn 大兄弟,解决了吗。求告知
@lovecn
@HeightHeight
解决方法:
修改文件vendor/jonnyw/php-phantomjs/src/JonnyW/PhantomJs/DependencyInjection/ServiceContainer.php中的load()函数加个参数并给个默认值:
详情:https://doc.querylist.cc/site/index/doc/40
@Jaeger 感谢,收到!
如果试windows 下的话 在哪 设置PhantomJS二进制文件路径
@kakaluote 一样的吧 d:\bin\phantomjs.exe
楼主是怎么安装plantomjs文件的啊,我一直安装失败
composer require jaeger/querylist-phantomjs
laravel6.0不能安装,楼主是laravel几Class 'Tightenco\Collect\Support\Collection' not found 报错
jaeger / querylist-phantomjs 里面使用得jonnyw/php-phantomjs 版本太老了 ,最近更新是4年前得了,jonnyw/php-phantomjs中composer里面得包,版本太低了,没得最新版的么?