经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
php使用QueryList轻松采集JavaScript动态渲染页面
来源:cnblogs  作者:.Ronin  时间:2019/11/7 20:45:35  对本文有异议

QueryList使用jQuery的方式来做采集,拥有丰富的插件。

 

下面来演示QueryList使用PhantomJS插件抓取JS动态创建的页面内容。

推荐:《PHP教程

安装

使用Composer安装:

安装QueryList

1

2

composer require jaeger/querylist

GitHub: https://github.com/jae-jae/QueryList

安装PhantomJS插件

1

2

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

2

3

4

5

6

7

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:

1

2

$html = $ql->browser('https://m.toutiao.com')->getHtml();

print_r($html);

获取所有p标签文本内容:

1

2

$data = $ql->browser('https://m.toutiao.com')->find('p')->texts();

print_r($data->all());

输出:

1

2

3

4

5

6

7

Array

(

    [0] => 自拍模式开启!国庆假期我和国旗合个影

    [1] => 你旅途已开始 他们仍在自己的岗位上为你的假期保驾护航

    [2] => 喜极而泣,都教授终于回到地球了!

    //....

)

使用http代理:

1

2

3

4

5

6

// 更多选项可以查看文档: 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

自定义一个复杂的请求:

1

2

3

4

5

6

7

8

$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文件:

1

2

3

4

5

6

7

8

9

10

11

12

13

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

原文链接:http://www.cnblogs.com/heyue0117/p/11812806.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号