QueryList使用jQuery的方式來作採集,擁有豐富的插件。php
下面來演示QueryList
使用PhantomJS
插件抓取JS動態建立的頁面內容。html
使用Composer安裝:git
composer require jaeger/querylist
GitHub: https://github.com/jae-jae/QueryListgithub
composer require jaeger/querylist-phantomjs
PhantomJS官網:http://phantomjs.org ,下載對應平臺的PhantomJS二進制文件。瀏覽器
以採集「今日頭條」手機版爲例,「今日頭條」手機版基於React框架,內容是純動態渲染出來的。cookie
下面演示QueryList
的PhantomJs插件用法:composer
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標籤文本內容:ui
$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());