相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
- PHP中opcode緩存簡單用法分析
- thinkPHP控制器變量在模板中的顯示方法示例
- PHP move_uploaded_file() 函數(shù)(將上傳的文件移動(dòng)到新位置)
- dirname(__FILE__)的含義和應(yīng)用說明
- thinkPHP5框架實(shí)現(xiàn)分頁查詢功能的方法示例
- PHP中單雙號(hào)與變量
- PHP獲得當(dāng)日零點(diǎn)時(shí)間戳的方法分析
- Laravel ORM對Model::find方法進(jìn)行緩存示例詳解
- PHP讀寫文件高并發(fā)處理操作實(shí)例詳解
- 【CLI】利用Curl下載文件實(shí)時(shí)進(jìn)度條顯示的實(shí)現(xiàn)
利用PHP抓取百度閱讀的方法示例
前言
這篇文章主要介紹的是,如何利用PHP抓取百度閱讀的方法,下面話不多說,來一起看看吧。
抓取方法如下
首先在瀏覽器里打開閱讀頁面,查看源代碼后發(fā)現(xiàn)小說的內(nèi)容并不是直接寫在頁面里的,也就是說小說的內(nèi)容是通過異步加載而來的。
于是將chrome的開發(fā)者工具切到network一欄,刷新閱讀頁面,主要關(guān)注的是XHR和script兩個(gè)分類下。
經(jīng)過排查,發(fā)現(xiàn)在script分類下有個(gè)jsonp請求比較像是小說內(nèi)容,請求的地址是
http://wenku.baidu.com/content/49422a3769eae009581becba?m=8ed1dedb240b11bf0731336eff95093f&type=json&cn=1&_=1&t=1423309200&callback=wenku7
返回的是一個(gè)jsonp
字符串,然后我發(fā)現(xiàn),如果把地址里面的callback=wenku7
去掉,返回的就是一個(gè)json
字符串,這樣解析起來就方便不少,可以直接在php里面轉(zhuǎn)換成數(shù)組。
再來分析一下返回?cái)?shù)據(jù)的結(jié)構(gòu),返回的json
字符串之后是一個(gè)樹狀的結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都有一個(gè)t屬性和c屬性,t屬性用來指明這個(gè)節(jié)點(diǎn)的標(biāo)簽,比如h2 div等等,c屬性就是內(nèi)容了,但也有兩種可能,一個(gè)是字符串,另一個(gè)是數(shù)組,數(shù)組的每個(gè)元素都是一個(gè)節(jié)點(diǎn)。
這種結(jié)構(gòu)最好解析了,用一個(gè)遞歸就搞定
最終代碼如下:
<?php class BaiduYuedu { protected $bookId; protected $bookToken; protected $cookie; protected $result; public function __construct($bookId, $bookToken, $cookie){ $this->bookId = $bookId; $this->bookToken = $bookToken; $this->cookie = $cookie; } public static function parseNode($node){ $str = ''; if(is_string($node['c'])){ $str .= $node['c']; }else if(is_array($node['c'])){ foreach($node['c'] as $d){ $str .= self::parseNode($d); } } switch($node['t']){ case 'h2': $str .= "\n\n"; break; case 'br': case 'div': case 'p': $str .= "\n"; break; case 'img': case 'span': break; case 'obj': $tmp = '(' . self::parseNode($node['data'][0]) . ')'; $str .= str_replace("\n", '', $tmp); break; default: trigger_error('Unkown type:'.$node['t'], E_USER_WARNING); break; } return $str; } public function get($page = 1){ echo "getting page {$page}...\n"; $ch = curl_init(); $url = sprintf('http://wenku.baidu.com/content/%s/?m=%s&type=json&cn=%d', $this->bookId, $this->token, $page); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => 0, CURLOPT_HTTPHEADER => array('Cookie: '. $this->cookie) )); $ret = json_decode(curl_exec($ch), true); curl_close($ch); $str = ''; if(!empty($ret)){ $str .= self::parseNode($ret); $str .= $this->get($page + 1); } return $str; } public function start(){ $this->result = $this->get(); } public function getResult(){ return $this->result; } public function saveTo($path){ if(empty($this->result)){ trigger_error('Result is empty', E_USER_ERROR); return; } file_put_contents($path, $this->result); echo "save to {$path}\n"; } } //使用示例 $yuedu = new BaiduYuedu('49422a3769eae009581becba', '8ed1dedb240b11bf0731336eff95093f', '你的百度域cookie'); $yuedu->start(); $yuedu->saveTo('result.txt');