QueryList 簡介
QueryList是一款PHP採集工具(爬蟲),根據phpQuery基礎研發的。比phpQuery多封裝了cookie登錄。
其他優劣勢
繼承phpQuery, 同樣模倣jQuery
擁有通用的列表採集方案
封裝了模擬登錄、模擬瀏覽器動作、HTTP代理等複雜的網路請求
解決亂碼問題
擁有内容過濾功能,可使用jQuey選擇器來過濾内容
通過插件可以輕松實現諸如:
多線程採集
採集JavaScript動態渲染的頁面 (PhantomJS/headless WebKit)
圖片本地化
模擬瀏覽器行爲,如:提交Form表單
網頁爬蟲
環境要求
PHP >= 7.0
如果你的PHP版本還停留在PHP5,或者不會使用Composer,你可以選擇使用QueryList3,QueryList3支持php5.3以及手動安裝。
安裝
國内的業務研發人員需要先配置國内鏡像, 不然翻查composer垃圾堆可能卡死。
composer config -g repo.packagist composer https://packagist.phpcomposer.com
再通過Composer安裝:
composer require jaeger/querylist
使用
元素操作
採集「昵圖網」所有圖片地址,首先你需要加載目錄裡的autoload.php才可以, 還需要聲明使用命名空間。
require 'QueryList/vendor/autoload.php'; use QL\QueryList; QueryList::get('http://www.nipic.com')->find('img')->attrs('src');
採集百度搜索結果
$ql = QueryList::get('http://www.baidu.com/s?wd=QueryList'); $ql->find('title')->text(); // 獲取網站標題 $ql->find('meta[name=keywords]')->content; // 獲取網站頭部關鍵詞 $ql->find('h3>a')->texts(); //獲取搜索結果標題列表 $ql->find('h3>a')->attrs('href'); //獲取搜索結果鏈接列表 $ql->find('img')->src; //獲取第一張圖片的鏈接地址 $ql->find('img:eq(1)')->src; //獲取第二張圖片的鏈接地址 $ql->find('img')->eq(2)->src; //獲取第三張圖片的鏈接地址 // 遍歷所有圖片 $ql->find('img')->map(function($img){ echo $img->alt; //列印圖片的alt屬性 });
更多用法
$ql->find('#head')->append('<div>追加内容</div>')->find('div')->htmls(); $ql->find('.two')->children('img')->attrs('alt'); //獲取class爲two元素下的所有img孩子節點 //遍歷class爲two元素下的所有孩子節點 $data = $ql->find('.two')->children()->map(function ($item){ //用is判斷節點類型 if($item->is('a')){ return $item->text(); }elseif($item->is('img')) { return $item->alt; } }); $ql->find('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->... $ql->find('div > p')->add('div > ul')->filter(':has(a)')->find('p:first')->nextAll()->andSelf()->... $ql->find('div.old')->replaceWith( $ql->find('div.new')->clone())->appendTo('.trash')->prepend('Deleted')->...
列表採集
採集百度搜索結果列表的標題和鏈接:
$data = QueryList::get('http://www.baidu.com/s?wd=QueryList') // 設置採集槼則 ->rules([ 'title'=>array('h3','text'), 'link'=>array('h3>a','href') ]) ->query()->getData(); print_r($data->all());
採集結果:
Array ( [0] => Array ( [title] => QueryList|基於phpQuery的無比強大的PHP採集工具 [link] => http://www.baidu.com/link?url=GU_YbDT2IHk4ns1tjG2I8_vjmH0SCJEAPuuZN ) [1] => Array ( [title] => PHP 用QueryList抓取網頁内容 - wb145230 - 部落格園 [link] => http://www.baidu.com/link?url=zn0DXBnrvIF2ibRVW34KcRVFG1_bCdZvqvwIhUqiXaS ) [2] => Array ( [title] => 介紹- QueryList指導文档 [link] => http://www.baidu.com/link?url=pSypvMovqS4v2sWeQo5fDBJ4EoYhXYi0Lxx ) //... )
編碼轉換
// 輸出編碼:UTF-8,輸入編碼:GB2312 QueryList::get('https://top.etao.com')->encoding('UTF-8','GB2312')->find('a')->texts(); // 輸出編碼:UTF-8,輸入編碼:自動識別 QueryList::get('https://top.etao.com')->encoding('UTF-8')->find('a')->texts();
HTTP網路操作(GuzzleHttp)
攜帶cookie登錄新浪微博
//採集新浪微博需要登錄才能訪問的頁面 $ql = QueryList::get('http://weibo.com','param1=testvalue & params2=somevalue',[ 'headers' => [ //填寫從瀏覽器獲取到的cookie 'Cookie' => 'SINAGLOBAL=546064; wb_cmtLike_2112031=1; wvr=6;....' ] ]); //echo $ql->getHtml(); echo $ql->find('title')->text(); // 輸出: 我的首頁 微博-隨時隨地發現新鮮事
使用Http代理
$urlParams = ['param1' => 'testvalue','params2' => 'somevalue']; $opts = [ // 設置http代理 'proxy' => 'http://222.141.11.17:8118', //設置超時時間,單位:秒 'timeout' => 30, // 偽造http頭 'headers' => [ 'Referer' => 'https://querylist.cc/', 'User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'], 'Cookie' => 'abc=111;xxx=222' ] ]; $ql->get('http://httpbin.org/get',$urlParams,$opts); // echo $ql->getHtml();
模擬登錄
// 用post登錄 $ql = QueryList::post('http://xxxx.com/login',[ 'username' => 'admin', 'password' => '123456' ])->get('http://xxx.com/admin'); // 採集需要登錄才能訪問的頁面 $ql->get('http://xxx.com/admin/page'); // echo $ql->getHtml();
Form表單操作
模擬登陸GitHub
// 獲取QueryList實例 $ql = QueryList::getInstance(); // 獲取到登錄表單 $form = $ql->get('https://github.com/login')->find('form'); // 填寫GitHub用戶名和密碼 $form->find('input[name=login]')->val('your github username or email'); $form->find('input[name=password]')->val('your github password'); // 序列化表單數據 $fromData = $form->serializeArray(); $postData = []; foreach ($fromData as $item) { $postData[$item['name']] = $item['value']; } // 提交登錄表單 $actionUrl = 'https://github.com'.$form->attr('action'); $ql->post($actionUrl,$postData); // 判斷登錄是否成功 // echo $ql->getHtml(); $userName = $ql->find('.header-nav-current-user>.css-truncate-target')->text(); if($userName) { echo '登錄成功!歡迎你:'.$userName; }else{ echo '登錄失敗!'; }
Bind功能擴展
自定義擴展一個`myHttp`方法:
$ql = QueryList::getInstance(); //綁定一個myHttp方法到QueryList對象 $ql->bind('myHttp',function ($url){ // $this 爲當前的QueryList對象 $html = file_get_contents($url); $this->setHtml($html); return $this; }); //然後就可以通過注冊的名字來調用 $data = $ql->myHttp('https://toutiao.io')->find('h3 a')->texts(); print_r($data->all());
或者把實現體封裝到class,然後這樣綁定:
$ql->bind('myHttp',function ($url){ return new MyHttp($this,$url); });
插件使用
使用PhantomJS插件採集JavaScript動態渲染的頁面:
// 安裝時設置PhantomJS二進制文档路徑 $ql = QueryList::use(PhantomJs::class,'/usr/local/bin/phantomjs'); // 採集今日頭條手機版 $data = $ql->browser('https://m.toutiao.com')->find('p')->texts(); print_r($data->all()); // 使用HTTP代理 $ql->browser('https://m.toutiao.com',false,[ '--proxy' => '192.168.1.42:8080', '--proxy-type' => 'http' ])
使用CURL多線程插件,多線程採集GitHub排行榜:
$ql = QueryList::use(CurlMulti::class); $ql->curlMulti([ 'https://github.com/trending/php', 'https://github.com/trending/go', //.....more urls ]) // 每個任務成功完成調用此回調 ->success(function (QueryList $ql,CurlMulti $curl,$r){ echo "Current url:{$r['info']['url']} \r\n"; $data = $ql->find('h3 a')->texts(); print_r($data->all()); }) // 每個任務失敗回調 ->error(function ($errorInfo,CurlMulti $curl){ echo "Current url:{$errorInfo['info']['url']} \r\n"; print_r($errorInfo['error']); }) ->start([ // 最大並發數 'maxThread' => 10, // 錯誤重試次數 'maxTry' => 3, ]);
插件
[jae-jae/QueryList-PhantomJS](https://github.com/jae-jae/QueryList-PhantomJS): 使用PhantomJS採集JavaScript動態渲染的頁面
[jae-jae/QueryList-CurlMulti](https://github.com/jae-jae/QueryList-CurlMulti) : Curl多線程採集
[jae-jae/QueryList-AbsoluteUrl](https://github.com/jae-jae/QueryList-AbsoluteUrl) : 轉換URL相對路徑到絕對路徑
[jae-jae/QueryList-Rule-Google](https://github.com/jae-jae/QueryList-Rule-Google) : 谷歌搜索引擎
[jae-jae/QueryList-Rule-Baidu](https://github.com/jae-jae/QueryList-Rule-Baidu) : 百度搜索引擎
查看更多的QueryList插件和基於QueryList的産品:[QueryList社區力量](https://github.com/jae-jae/QueryList-Community)