PHP 使用 QueryList 轻松采集 JavaScript 动态渲染页面

2017-10-02 12:09:31 +08:00
 Jaeger

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

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

安装

使用 Composer 安装:

composer require jaeger/querylist

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

composer require jaeger/querylist-phantomjs

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

下载 PhantomJS 二进制文件

PhantomJS 官网:http://phantomjs.org ,下载对应平台的 PhantomJS 二进制文件。

插件 API

使用

以采集「今日头条」手机版为例,「今日头条」手机版基于 React 框架,内容是纯动态渲染出来的。

下面演示QueryList的 PhantomJs 插件用法:

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

获取动态渲染的 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'
])

自定义一个复杂的请求:

$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());
6618 次点击
所在节点    PHP
6 条回复
hugee
2017-10-02 12:54:45 +08:00
这东西不错
hahasong
2017-10-02 14:48:50 +08:00
两天实现了 headless
hronro
2017-10-02 17:12:35 +08:00
PhantomJS 已经停止维护了吧,为什么不用 Chrome headless 呢
HYSS
2017-10-02 19:26:56 +08:00
如何做到不开启 phantomjs 的 用 php 开启 phantomjs ?
fuxkcsdn
2017-10-02 19:53:25 +08:00
@hronro 用 Chrome headless 的话还用啥 php😂
半官方的封装 api https://github.com/GoogleChrome/puppeteer 不要太好用,我是不信会写爬虫的 phper 不会简单的 nodejs
zackkk
2017-10-03 07:45:11 +08:00
可以理解为,ajax 加载的内容也可以采么

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/395121

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX