背景:想做一个公众号文章资源APP,发现搜狗有搜索公众号文章功能,果断开撸。http://wxiread.com (用CMS搭了个简易的站)。
Step1.分析栏目及接口
搜狗分了20个栏目,分别是 热门,推荐,段子手,养生堂,私房话… 对应地址从 /pcindex/pc/pc_0 到 /pcindex/pc/pc_19 , 如:http://weixin.sogou.com/pcindex/pc/pc_0/1.html [1.html为分页号]。 整理栏目对应关系见表如下:
Step2.分析列表结构
文章列表页由 li 节点构成,li 的ID可看做文章ID,li子节点包括文章标题,描述信息,作者,作者头像等。
Step3.使用QueryList采集文章基本信息
QueryList 是一个基于PHP的DOM解析工具,功能强大,语法类似于JQuery;详细使用可查看官方文档
代码如下:
protected function get_article_list($url)
{
//获取文章LI ID规则
$rules = array(
'article_id' => array('li', 'id'),//文章ID
'inner_html' => array('li', 'html')
);
//递归获取LI节点内容
$data = QueryList::Query($url, $rules)->getData(function($li) {
$id = $li['article_id'];
$info = QueryList::Query($li['inner_html'], array(
'article_url' => array(".wx-img-box > a", "href"), //文章地址
'author_url' => array(".pos-wxrw > a", "href"), //作者地址
'author_avatar' => array(".pos-wxrw > a > p > img", "src"), //作者头像
'article_thumb' => array(".wx-img-box > a > img", "src"), //文章缩略图
'author_name' => array(".pos-wxrw > a > p:eq(1)", "text"), //作者名称
'article_title' => array(".wx-news-info2 > h4", "text"), //文章标题
'article_des' => array(".wx-news-info", "text"), //文章简介
'article_create_at' => array(".wx-news-info2 [v]", "v"), //文章标题
'article_hits' => array(".wx-news-info2 > .s-p", "text", "", function($i){ preg_match('/\d+/', $i, $ms); return (int)$ms[0];}), //文章标题
))->data;
unset($info['inner_html']);
$info[0]['article_id'] = $id;
$info[0]['article_hits'] = intval($info[0]['article_hits']);
return $info[0];
});
return $data;
}
Step4.获取文章详情