php实现爬取和分析知乎用户数据,php
背景说明:小拽利用php的curl写的爬虫,实验性的爬取了知乎5w用户的基本信息;同时,针对爬取的数据,进行了简单的分析呈现。
php的spider代码和用户dashboard的展现代码,整理后上传github,在个人博客和公众号更新代码库,程序仅供娱乐和学习交流;如果有侵犯知乎相关权益,请尽快联系本人删除。
无图无真相
移动端分析数据截图
pc端分析数据截图
整个爬取,分析,展现过程大概分如下几步,小拽将分别介绍
- curl爬取知乎网页数据
- 正则分析知乎网页数据
- 数据数据入库和程序部署
- 数据分析和呈现
curl爬取网页数据
PHP的curl扩展是PHP支持的,允许你与各种服务器使用各种类型的协议进行连接和通信的库。是一个非常便捷的抓取网页的工具,同时,支持多线程扩展。
本程序抓取的是知乎对外提供用户访问的个人信息页面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页面中发现了新的用户,可用于爬虫
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))\"?.+ alt="php实现爬取和分析知乎用户数据,php_PHP教程" >/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控制,代码如下
// 获取用户头像 preg_match('/<img .+src=\"?([^\s]+\.(jpg|gif|bmp|bnp|png))\"?.+ alt="php实现爬取和分析知乎用户数据,php_PHP教程" >/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];
不足和待学习
整个过程中涉及php,shell,js,css,html,正则等语言和部署等基础知识,但还有诸多需要改进完善,小拽特此记录,后续补充例:
- php 采用multicul进行多线程。
- 正则匹配进一步优化
- 部署和抓取过程采用redis提升存储
- 移动端布局的兼容性提升
- js的模块化和sass书写css。
您可能感兴趣的文章:
- php IIS日志分析搜索引擎爬虫记录程序
- php 向访客和爬虫显示不同的内容
- 一个PHP实现的轻量级简单爬虫
- PHP实现简单爬虫的方法
- PHP代码实现爬虫记录——超管用
- PHP爬虫之百万级别知乎用户数据爬取与分析

PHP仍然流行的原因是其易用性、靈活性和強大的生態系統。 1)易用性和簡單語法使其成為初學者的首選。 2)與web開發緊密結合,處理HTTP請求和數據庫交互出色。 3)龐大的生態系統提供了豐富的工具和庫。 4)活躍的社區和開源性質使其適應新需求和技術趨勢。

PHP和Python都是高層次的編程語言,廣泛應用於Web開發、數據處理和自動化任務。 1.PHP常用於構建動態網站和內容管理系統,而Python常用於構建Web框架和數據科學。 2.PHP使用echo輸出內容,Python使用print。 3.兩者都支持面向對象編程,但語法和關鍵字不同。 4.PHP支持弱類型轉換,Python則更嚴格。 5.PHP性能優化包括使用OPcache和異步編程,Python則使用cProfile和異步編程。

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器