当前位置: 移动技术网 > IT编程>开发语言>PHP > php使用QueryList轻松采集js动态渲染页面方法

php使用QueryList轻松采集js动态渲染页面方法

2018年09月23日  | 移动技术网IT编程  | 我要评论

dw战队,文莱吴尊,网游之机械尖兵

querylist使用jquery的方式来做采集,拥有丰富的插件。下面来演示querylist使用phantomjs插件抓取js动态创建的页面内容。

一、安装

使用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 ,下载对应平台的phantomjs二进制文件。

三、插件api

querylist browser($url,$debug = false,$commandopt = []):使用浏览器打开连接

四、使用

以采集「今日头条」手机版为例,「今日头条」手机版基于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.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'
])

3.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());

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网