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

php使用QueryList輕鬆擷取JavaScript動態渲染頁面

藏色散人
藏色散人轉載
2019-10-15 14:25:392901瀏覽

QueryList使用jQuery的方式來做採集,擁有豐富的外掛。

下面來示範QueryList使用PhantomJS外掛程式抓取JS動態建立的頁面內容。

推薦:《PHP教學

安裝

使用Composer安裝:

##使用Composer安裝:

安裝QueryList

composer require jaeger/querylist
GitHub: https://github.com/jae-jae/QueryList

安裝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外掛用法:

安裝外掛

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:

$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'
])

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

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除