背景說明:小拽利用php的curl寫的爬蟲,實驗性的爬取了知乎5w用戶的基本信息;同時,針對爬取的數據,進行了簡單的分析呈現。demo 地址php
php的spider代碼和用戶dashboard的展示代碼,整理後上傳github,在我的博客和公衆號更新代碼庫,程序僅供娛樂和學習交流;若是有侵犯知乎相關權益,請儘快聯繫本人刪除。css
移動端分析數據截圖html
pc端分析數據截圖mysql
整個爬取,分析,展示過程大概分以下幾步,小拽將分別介紹git
curl爬取知乎網頁數據github
正則分析知乎網頁數據web
數據數據入庫和程序部署redis
數據分析和呈現sql
PHP的curl擴展是PHP支持的,容許你與各類服務器使用各類類型的協議進行鏈接和通訊的庫。是一個很是便捷的抓取網頁的工具,同時,支持多線程擴展。shell
本程序抓取的是知乎對外提供用戶訪問的我的信息頁面https://www.zhihu.com/people/xxx,抓取過程須要攜帶用戶cookie才能獲取頁面。直接上碼
獲取頁面cookie
// 登陸知乎,打開我的中心,打開控制檯,獲取cookie document.cookie "_za=67254197-3wwb8d-43f6-94f0-fb0e2d521c31; _ga=GA1.2.2142818188.1433767929; q_c1=78ee1604225d47d08cddd8142a08288b23|1452172601000|1452172601000; _xsrf=15f0639cbe6fb607560c075269064393; cap_id="N2QwMTExNGQ0YTY2NGVddlMGIyNmQ4NjdjOTU0YTM5MmQ=|1453444256|49fdc6b43dc51f702b7d6575451e228f56cdaf5d"; __utmt=1; unlock_ticket="QUJDTWpmM0lsZdd2dYQUFBQVlRSlZUVTNVb1ZaNDVoQXJlblVmWGJ0WGwyaHlDdVdscXdZU1VRPT0=|1453444421|c47a2afde1ff334d416bafb1cc267b41014c9d5f"; __utma=51854390.21428dd18188.1433767929.1453187421.1453444257.3; __utmb=51854390.14.8.1453444425011; __utmc=51854390; __utmz=51854390.1452846679.1.dd1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmv=51854390.100-1|2=registration_date=20150823=1^dd3=entry_date=20150823=1"
抓取我的中心頁面
經過curl,攜帶cookie,先抓取本人中心頁面
/** * 經過用戶名抓取我的中心頁面並存儲 * * @param $username str :用戶名 flag * @return boolean :成功與否標誌 */ public function spiderUser($username) { $cookie = "xxxx" ; $url_info = 'http://www.zhihu.com/people/' . $username; //此處cui-xiao-zhuai表明用戶ID,能夠直接看url獲取本人id $ch = curl_init($url_info); //初始化會話 curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_COOKIE, $cookie); //設置請求COOKIE curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //將curl_exec()獲取的信息以文件流的形式返回,而不是直接輸出。 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $result = curl_exec($ch); file_put_contents('/home/work/zxdata_ch/php/zhihu_spider/file/'.$username.'.html',$result); return true; }
對於抓取過來的網頁進行存儲,要想進行進一步的爬取,頁面必須包含有可用於進一步爬取用戶的連接
。經過對知乎頁面分析發現:在我的中心頁面中有關注人和部分點贊人和被關注人。
以下所示
// 抓取的html頁面中發現了新的用戶,可用於爬蟲 <a class="zm-item-link-avatar avatar-link" href="/people/new-user" data-tip="p$t$new-user">
ok,這樣子就能夠經過本身-》關注人-》關注人的關注人-》。。。進行不斷爬取。接下來就是經過正則匹配提取該信息
// 匹配到抓取頁面的全部用戶 preg_match_all('/\/people\/([\w-]+)\"/i', $str, $match_arr); // 去重合併入新的用戶數組,用戶進一步抓取 self::$newUserArr = array_unique(array_merge($match_arr[1], self::$newUserArr));
到此,整個爬蟲過程就能夠順利進行了。
若是須要大量的抓取數據,能夠研究下curl_multi
和pcntl
進行多線程的快速抓取,此處不作贅述。
經過正則能夠進一步匹配出更多的該用戶數據,直接上碼。
// 獲取用戶頭像 preg_match('/<img.+src=\"?([^\s]+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', $str, $match_img); $img_url = $match_img[1]; // 匹配用戶名: // <span class="name">崔小拽</span> preg_match('/<span.+class=\"?name\"?>([\x{4e00}-\x{9fa5}]+).+span>/u', $str, $match_name); $user_name = $match_name[1]; // 匹配用戶簡介 // class bio span 中文 preg_match('/<span.+class=\"?bio\"?.+\>([\x{4e00}-\x{9fa5}]+).+span>/u', $str, $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', $str, $match_sex); $user_sex = $match_sex[1]; // 匹配地區 //<span class="location item" title="北京"> preg_match('/<span.+class=\"?location.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_city); $user_city = $match_city[1]; // 匹配工做 //<span class="employment item" title="人見人罵的公司">人見人罵的公司</span> preg_match('/<span.+class=\"?employment.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $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">程序猿</a></span> preg_match('/<span.+class=\"?position.+\"?.+\"([\x{4e00}-\x{9fa5}]+).+\">/u', $str, $match_position); $user_position = $match_position[1]; // 匹配學歷 // <span class="education item" title="研究僧">研究僧</span> preg_match('/<span.+class=\"?education.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_education); $user_education = $match_education[1]; // 工做狀況 // <span class="education-extra item" title='挨踢'>挨踢</span> preg_match('/<span.+class=\"?education-extra.+\"?.+>([\x{4e00}- \x{9fa5}]+)</u', $str, $match_education_extra); $user_education_extra = $match_education_extra[1]; // 匹配關注話題數量 // class="zg-link-litblue"><strong>41 個話題</strong></a> preg_match('/class=\"?zg-link-litblue\"?><strong>(\d+)\s.+strong>/i', $str, $match_topic); $user_topic = $match_topic[1]; // 關注人數 // <span class="zg-gray-normal">關注了 preg_match_all('/<strong>(\d+)<.+<label>/i', $str, $match_care); $user_care = $match_care[1][0]; $user_be_careed = $match_care[1][1]; // 歷史瀏覽量 // <span class="zg-gray-normal">我的主頁被 <strong>17</strong> 人瀏覽</span> preg_match('/class=\"?zg-gray-normal\"?.+>(\d+)<.+span>/i', $str, $match_browse); $user_browse = $match_browse[1];
在抓取的過程當中,有條件的話,必定要經過redis入庫,確實能提高抓取和入庫效率。沒有條件的話只能經過sql優化。這裏來幾發心德。
數據庫表設計索引必定要慎重。在spider爬取的過程當中,建議出了用戶名,左右字段都不要索引,包括主鍵都不要,儘量的提升入庫效率
,試想5000w的數據,每次添加一個,創建索引須要多少消耗。等抓取完畢,須要分析數據時,批量創建索引。
數據入庫和更新操做,必定要批量。 mysql 官方給出的增刪改的建議和速度:http://dev.mysql.com/doc/refman/5.7/en/insert-speed.html
# 官方的最優批量插入 INSERT INTO yourtable VALUES (1,2), (5,5), ...;
部署操做。程序在抓取過程當中,有可能會出現異常掛掉,爲了保證高效穩定,儘量的寫一個定時腳本。每隔一段時間幹掉,從新跑,這樣即便異常掛掉也不會浪費太多寶貴時間,畢竟,time is money。
#!/bin/bash # 幹掉 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控制,代碼以下
/*兼容性和響應式div設計*/ @media screen and (max-width: 480px) { body{ padding: 0 ; } .adapt-div { width: 100% ; float: none ; margin: 20px 0; } .half-div { height: 350px ; margin-bottom: 10px; } .whole-div { height: 350px; } } <!-- 整塊完整佈局,半塊在web端採用float的方式,移動端去掉--> .half-div { width: 48%; height: 430px; margin: 1%; float: left } .whole-div { width: 98%; height: 430px; margin: 1%; float: left }
整個過程當中涉及php,shell,js,css,html,正則等語言和部署等基礎知識,但還有諸多須要改進完善,小拽特此記錄,後續補充例:
php 採用multicul進行多線程。
正則匹配進一步優化
部署和抓取過程採用redis提高存儲
移動端佈局的兼容性提高
js的模塊化和sass書寫css。
【轉載請註明:php爬蟲:知乎用戶數據爬取和分析 | 靠譜崔小拽 】