queryList 配合 PhantomJS 插件 采集 JavaScript 动态渲染的页面
百度搜索 queryList
,文档地址 。
由于 PhantomJS
对 laravel
的引入支持不好,所以我将两者安装到项目根目录的 sdk/queryList/
下。
"jaeger/querylist": "^4.2",
"jaeger/querylist-phantomjs": "^4.0"
再下载 PhantomJS 二进制文件,我也放到了 sdk/
目录下。
Laravel 中在 console
中写逻辑代码,以抓取百度直播网页版为例:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class Phantomjs extends Command
{
protected $signature = 'js:test';
protected $description = '....';
protected $ql;
public function __construct(){
parent::__construct();
}
public function handle()
{
require_once base_path().'/sdk/queryList/vendor/autoload.php';
$this->ql = \QL\QueryList::getInstance();
// 设置PhantomJS二进制文件路径
$this->ql->use(\QL\Ext\PhantomJs::class,'/www/wwwroot/blog/sdk/phantomjs-2.1.1/bin/phantomjs');
while(true){
$this->bd();
sleep(5);
}
}
public function bd(){
$room_id = $this->bd_roomid;
$url = 'http://mbd.baidu.com/webpage?type=live&action=liveshow&room_id='.$room_id;
$data = $this->ql->browser(function (\JonnyW\PhantomJs\Http\RequestInterface $r) use ($url){
$r->setMethod('GET');
$r->setUrl($url);
$r->setTimeout(10000); // 10 seconds
$r->setDelay(3); // 3 seconds 这里的延时很重要
return $r;
})
->rules([
'avatar' => ['.msg-box-avatar', 'src'],
'username' => ['.msg-box-name', 'text'],
'text' => ['.msg-box-text', 'text'],
])
->range('.msg-box')
->queryData(); //array
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: