到此,整个爬虫过程就可以顺利进行了。
如果需要大量的抓取数据,可以研究下curl_multi
和pcntl
进行多线程的快速抓取,此处不做赘述。
分析用户数据,提供分析
通过正则可以进一步匹配出更多的该用户数据,直接上码。
/i',$match_img);
$img_url = $match_img[1];
// 匹配用户名:
// <span class="name">崔小拽
preg_match('/<span.+class="?name"?>([x{4e00}-x{9fa5}]+).+span>/u',$match_name);
$user_name = $match_name[1];
// 匹配用户简介
// class bio span 中文
preg_match('/<span.+class="?bio"?.+>([x{4e00}-x{9fa5}]+).+span>/u',$match_title);
$user_title = $match_title[1];
// 匹配性别
//<input type="radio" name="gender" value="1" checked="checked" class="male"/> 男
// gender value1 ;结束 中文
preg_match('/<input.+name="?gender"?.+value="?1"?.+([x{4e00}-x{9fa5}]+).+;/u',$match_sex);
$user_sex = $match_sex[1];
// 匹配地区
//<span class="location item" title="北京">
preg_match('/<span.+class="?location.+"?.+"([x{4e00}-x{9fa5}]+)">/u',$match_city);
$user_city = $match_city[1];
// 匹配工作
//<span class="employment item" title="人见人骂的公司">人见人骂的公司
preg_match('/<span.+class="?employment.+"?.+"([x{4e00}-x{9fa5}]+)">/u',$match_employment);
$user_employ = $match_employment[1];
// 匹配职位
// <span class="position item" title="程序猿"><a href="/topic/19590046" title="程序猿" class="topic-link" data-token="19590046" data-topicid="13253">程序猿
preg_match('/<span.+class="?position.+"?.+"([x{4e00}-x{9fa5}]+).+">/u',$match_position);
$user_position = $match_position[1];
// 匹配学历
// <span class="education item" title="研究僧">研究僧
preg_match('/<span.+class="?education.+"?.+"([x{4e00}-x{9fa5}]+)">/u',$match_education);
$user_education = $match_education[1];
// 工作情况
//
preg_match('/<span.+class="?education-extra.+"?.+>([x{4e00}-
x{9fa5}]+)</u',$match_education_extra);
$user_education_extra = $match_education_extra[1];
// 匹配关注话题数量
// class="zg-link-litblue">
41 个话题
preg_match('/class="?zg-link-litblue"?>
(d+)s.+h3>/i',$match_topic);
$user_topic = $match_topic[1];
// 关注人数
// <span class="zg-gray-normal">关注了
preg_match_all('/
(d+)<.+
在抓取的过程中,有条件的话,一定要通过redis入库,确实能提升抓取和入库效率。没有条件的话只能通过sql优化。这里来几发心德。
数据库表设计索引一定要慎重。在spider爬取的过程中,建议出了用户名,左右字段都不要索引,包括主键都不要,尽可能的提高入库效率
,试想5000w的数据,每次添加一个,建立索引需要多少消耗。等抓取完毕,需要分析数据时,批量建立索引。
数据入库和更新操作,一定要批量。 mysql 官方给出的增删改的建议和速度:http://dev.mysql.com/doc/refman/5.7/en/insert-speed.html
部署操作。程序在抓取过程中,有可能会出现异常挂掉,为了保证高效稳定,尽可能的写一个定时脚本。每隔一段时间干掉,重新跑,这样即使异常挂掉也不会浪费太多宝贵时间,毕竟,time is money。
干掉
ps aux |grep spider |awk '{print $2}'|xargs kill -9
sleep 5s
重新跑
nohup /home/cuixiaohuan/lamp/php5/bin/php /home/cuixiaohuan/php/zhihu_spider/spider_new.php &
数据分析呈现
数据的呈现主要使用echarts 3.0,感觉对于移动端兼容还不错。兼容移动端的页面响应式布局主要通过几个简单的css控制,代码如下
/i',$match_browse);
$user_browse = $match_browse[1];
不足和待学习
整个过程中涉及php,shell,js,css,html,正则等语言和部署等基础知识,但还有诸多需要改进完善,小拽特此记录,后续补充例:
- php 采用multicul进行多线程。
- 正则匹配进一步优化
- 部署和抓取过程采用redis提升存储
- 移动端布局的兼容性提升
- js的模块化和sass书写css。
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!