利用PHP抓取百度阅读的方法示例

首先在浏览器里打开阅读页面,查看源代码后发现小说的内容并不是直接写在页面里的,也就是说小说的内容是通过异步加载而来的。

于是将chrome的开发者工具切到network一栏,刷新阅读页面,主要关注的是XHR和script两个分类下。

经过排查,发现在script分类下有个jsonp请求比较像是小说内容,请求的地址是

?m=8ed1dedb240b11bf0731336eff95093f&type=json&cn=1&_=1&t=1423309200&callback=wenku7

返回的是一个jsonp字符串,然后我发现,如果把地址里面的callback=wenku7去掉,返回的就是一个json字符串,这样解析起来就方便不少,可以直接在php里面转换成数组。

再来分析一下返回数据的结构,返回的json字符串之后是一个树状的结构,每个节点都有一个t属性和c属性,t属性用来指明这个节点的标签,比如h2 div等等,c属性就是内容了,但也有两种可能,一个是字符串,另一个是数组,数组的每个元素都是一个节点。

这种结构最好解析了,用一个递归就搞定

最终代码如下:

<?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');

这个类前两个参数可以从小说的介绍页面获得,第一个参数bookId就是url里ebook后面跟着的字符串,第二个参数bookToken在页面源代码搜索bdjsonUrl,m参数后面的那个字符串就是。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7ec95769c8b67ef09c46b9a449d28646.html