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

yipeiwu_com7年前PHP代码库

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

相关文章

php脚本守护进程原理与实现方法详解

本文实例讲述了php脚本守护进程原理与实现方法。分享给大家供大家参考,具体如下: 思路: 1. while 循环,若当前没有数据要操作可以休眠; 2. crontab 脚本每隔固定时间段...

自己写了一个php检测文件编码的函数

关于文件编码的检测,百度一下一大把都是,但是确实没有能用的、 很多人建议 mb_detect_encoding 检测,可是不知为何我这不成功,什么都没输出、 看到有人写了个增强版,用 B...

php 获取文件后缀名,并判断是否合法的函数

核心代码 /** * 获取文件后缀名,并判断是否合法 * * @param string $file_name * @param array $allow_type * @...

php daddslashes()和 saddslashes()有哪些区别分析

//GPC过滤,自动转义$_GET,$_POST,$_COOKIE中的特殊字符,防止SQL注入攻击 $_GET = saddslashes($_GET); $_POST = saddsl...

初级的用php写的采集程序

可以先用这个采集然后在用帝国处理 <?php ###################################################################...