当前位置:首页 > PHP教程 > php高级应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-10-29 10:26:42 浏览: 评论:0 

这篇文章给大家分享了php使用QueryList轻松采集js动态渲染页面的相关知识点内容,有兴趣的朋友学习下。

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.安装插件

  1. use QL\QueryList; 
  2. use QL\Ext\PhantomJs; 
  3.    
  4. $ql = QueryList::getInstance(); 
  5. // 安装时需要设置PhantomJS二进制文件路径 
  6. $ql->use(PhantomJs::class,'/usr/local/bin/phantomjs'); 
  7. //or Custom function name 
  8. $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());

输出:

  1. Array( 
  2.   [0] => 自拍模式开启!国庆假期我和国旗合个影 
  3.   [1] => 你旅途已开始 他们仍在自己的岗位上为你的假期保驾护航 
  4.   [2] => 喜极而泣,都教授终于回到地球了!  //....) 

使用http代理:

  1. // 更多选项可以查看文档:  
  2. http://phantomjs.org/api/command-line.html 
  3. $ql->browser('https://m.toutiao.com',true,[   
  4. // 使用http代理  
  5. '--proxy' => '192.168.1.42:8080',  '--proxy-type' => 'http' 
  6. ]) 

3.Example-2

自定义一个复杂的请求:

  1. $data = $ql->browser(function (\JonnyW\PhantomJs\Http\RequestInterface $r){ 
  2.   $r->setMethod('GET'); 
  3.   $r->setUrl('https://m.toutiao.com'); 
  4.   $r->setTimeout(10000); // 10 seconds 
  5.   $r->setDelay(3); // 3 seconds 
  6.   return $r
  7. })->find('p')->texts(); 
  8.    
  9. print_r($data->all()); 

开启debug模式,并从本地加载cookie文件:

  1. $data = $ql->browser(function (\JonnyW\PhantomJs\Http\RequestInterface $r){ 
  2.   $r->setMethod('GET'); 
  3.   $r->setUrl('https://m.toutiao.com'); 
  4.   $r->setTimeout(10000); // 10 seconds 
  5.   $r->setDelay(3); // 3 seconds 
  6.   return $r
  7. },true,[ 
  8.   '--cookies-file' => '/path/to/cookies.txt' 
  9. ])->rules([ 
  10.   'title' => ['p','text'], 
  11.   'link' => ['a','href'
  12. ])->query()->getData(); 
  13.    
  14. print_r($data->all());

Tags: QueryList php采集js

分享到: