首頁  >  文章  >  後端開發  >  php如何使用QueryList輕鬆擷取js動態渲染頁面?

php如何使用QueryList輕鬆擷取js動態渲染頁面?

青灯夜游
青灯夜游原創
2018-09-10 17:31:193406瀏覽

本章來介紹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.安裝外掛程式

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如何使用QueryList輕鬆擷取js動態渲染頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn