search
HomeBackend DevelopmentPHP TutorialA brief discussion on how to use PHP to crawl and analyze Zhihu user data

本文给大家介绍的是利用php的curl编写的爬取知乎用户数据的爬虫,并分析用户的各种属性。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

A brief discussion on how to use PHP to crawl and analyze Zhihu user data

移动端分析数据截图

A brief discussion on how to use PHP to crawl and analyze Zhihu user data

pc端分析数据截图

A brief discussion on how to use PHP to crawl and analyze Zhihu user data

整个爬取,分析,展现过程大概分如下几步,小拽将分别介绍

  • 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页面中发现了新的用户,可用于爬虫
<a class="zm-item-link-avatar avatar-link" href="/people/new-user" data-tip="p$t$new-user">

ok,这样子就可以通过自己-》关注人-》关注人的关注人-》。。。进行不断爬取。接下来就是通过正则匹配提取该信息

 代码如下:

// 匹配到抓取页面的所有用户
preg_match_all(&#39;/\/people\/([\w-]+)\"/i&#39;, $str, $match_arr);
// 去重合并入新的用户数组,用户进一步抓取
self::$newUserArr = array_unique(array_merge($match_arr[1], self::$newUserArr));

到此,整个爬虫过程就可以顺利进行了。

如果需要大量的抓取数据,可以研究下curl_multipcntl进行多线程的快速抓取,此处不做赘述。

分析用户数据,提供分析

通过正则可以进一步匹配出更多的该用户数据,直接上码。

// 获取用户头像
preg_match(&#39;/<img .+src=\"?([^\s]+\.(jpg|gif|bmp|bnp|png))\"?.+ alt="A brief discussion on how to use PHP to crawl and analyze Zhihu user data" >/i&#39;, $str, $match_img);
$img_url = $match_img[1];

// 匹配用户名:
// <span class="name">崔小拽</span>
preg_match(&#39;/<span.+class=\"?name\"?>([\x{4e00}-\x{9fa5}]+).+span>/u&#39;, $str, $match_name);
$user_name = $match_name[1];

// 匹配用户简介
// class bio span 中文
preg_match(&#39;/<span.+class=\"?bio\"?.+\>([\x{4e00}-\x{9fa5}]+).+span>/u&#39;, $str, $match_title);
$user_title = $match_title[1];

// 匹配性别
//<input type="radio" name="gender" value="1" checked="checked" class="male"/> 男  
// gender value1 ;结束 中文
preg_match(&#39;/<input.+name=\"?gender\"?.+value=\"?1\"?.+([\x{4e00}-\x{9fa5}]+).+\;/u&#39;, $str, $match_sex);
$user_sex = $match_sex[1];

// 匹配地区
//<span class="location item" title="北京">
preg_match(&#39;/<span.+class=\"?location.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u&#39;, $str, $match_city);
$user_city = $match_city[1];

// 匹配工作
//<span class="employment item" title="人见人骂的公司">人见人骂的公司</span>
preg_match(&#39;/<span.+class=\"?employment.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u&#39;, $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(&#39;/<span.+class=\"?position.+\"?.+\"([\x{4e00}-\x{9fa5}]+).+\">/u&#39;, $str, $match_position);
$user_position = $match_position[1];

// 匹配学历
// <span class="education item" title="研究僧">研究僧</span>
preg_match(&#39;/<span.+class=\"?education.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u&#39;, $str, $match_education);
$user_education = $match_education[1];

// 工作情况
// <span class="education-extra item" title=&#39;挨踢&#39;>挨踢</span>
preg_match(&#39;/<span.+class=\"?education-extra.+\"?.+>([\x{4e00}-
\x{9fa5}]+)</u&#39;, $str, $match_education_extra);
$user_education_extra = $match_education_extra[1];


// 匹配关注话题数量
// class="zg-link-litblue"><strong>41 个话题</strong></a>
preg_match(&#39;/class=\"?zg-link-litblue\"?><strong>(\d+)\s.+strong>/i&#39;, $str, $match_topic);
$user_topic = $match_topic[1];

// 关注人数
// <span class="zg-gray-normal">关注了
preg_match_all(&#39;/<strong>(\d+)<.+<label>/i&#39;, $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(&#39;/class=\"?zg-gray-normal\"?.+>(\d+)<.+span>/i&#39;, $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 &#39;{print $2}&#39;|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(&#39;/<img .+src=\"?([^\s]+\.(jpg|gif|bmp|bnp|png))\"?.+ alt="A brief discussion on how to use PHP to crawl and analyze Zhihu user data" >/i&#39;, $str, $match_img);
$img_url = $match_img[1];

// 匹配用户名:
// <span class="name">崔小拽</span>
preg_match(&#39;/<span.+class=\"?name\"?>([\x{4e00}-\x{9fa5}]+).+span>/u&#39;, $str, $match_name);
$user_name = $match_name[1];

// 匹配用户简介
// class bio span 中文
preg_match(&#39;/<span.+class=\"?bio\"?.+\>([\x{4e00}-\x{9fa5}]+).+span>/u&#39;, $str, $match_title);
$user_title = $match_title[1];

// 匹配性别
//<input type="radio" name="gender" value="1" checked="checked" class="male"/> 男  
// gender value1 ;结束 中文
preg_match(&#39;/<input.+name=\"?gender\"?.+value=\"?1\"?.+([\x{4e00}-\x{9fa5}]+).+\;/u&#39;, $str, $match_sex);
$user_sex = $match_sex[1];

// 匹配地区
//<span class="location item" title="北京">
preg_match(&#39;/<span.+class=\"?location.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u&#39;, $str, $match_city);
$user_city = $match_city[1];

// 匹配工作
//<span class="employment item" title="人见人骂的公司">人见人骂的公司</span>
preg_match(&#39;/<span.+class=\"?employment.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u&#39;, $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(&#39;/<span.+class=\"?position.+\"?.+\"([\x{4e00}-\x{9fa5}]+).+\">/u&#39;, $str, $match_position);
$user_position = $match_position[1];

// 匹配学历
// <span class="education item" title="研究僧">研究僧</span>
preg_match(&#39;/<span.+class=\"?education.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u&#39;, $str, $match_education);
$user_education = $match_education[1];

// 工作情况
// <span class="education-extra item" title=&#39;挨踢&#39;>挨踢</span>
preg_match(&#39;/<span.+class=\"?education-extra.+\"?.+>([\x{4e00}-
\x{9fa5}]+)</u&#39;, $str, $match_education_extra);
$user_education_extra = $match_education_extra[1];


// 匹配关注话题数量
// class="zg-link-litblue"><strong>41 个话题</strong></a>
preg_match(&#39;/class=\"?zg-link-litblue\"?><strong>(\d+)\s.+strong>/i&#39;, $str, $match_topic);
$user_topic = $match_topic[1];

// 关注人数
// <span class="zg-gray-normal">关注了
preg_match_all(&#39;/<strong>(\d+)<.+<label>/i&#39;, $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(&#39;/class=\"?zg-gray-normal\"?.+>(\d+)<.+span>/i&#39;, $str, $match_browse);
$user_browse = $match_browse[1];

推荐学习:《PHP视频教程

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
如何使用 PHP 爬虫爬取大数据如何使用 PHP 爬虫爬取大数据Jun 14, 2023 pm 12:52 PM

随着数据时代的到来,数据量以及数据类型的多样化,越来越多的企业和个人需要获取并处理海量数据。这时,爬虫技术就成为了一个非常有效的方法。本文将介绍如何使用PHP爬虫来爬取大数据。一、爬虫介绍爬虫是一种自动获取互联网信息的技术。其原理是通过编写程序在网络上自动获取并解析网站内容,并将所需的数据抓取出来进行处理或储存。在爬虫程序的演化过程中,已经出现了许多成熟

高性能PHP爬虫的实现方法高性能PHP爬虫的实现方法Jun 13, 2023 pm 03:22 PM

随着互联网的发展,网页中的信息量越来越大,越来越深入,很多人需要从海量的数据中快速地提取出自己需要的信息。此时,爬虫就成了重要的工具之一。本文将介绍如何使用PHP编写高性能的爬虫,以便快速准确地从网络中获取所需的信息。一、了解爬虫基本原理爬虫的基本功能就是模拟浏览器去访问网页,并获取其中的特定信息。它可以模拟用户在网页浏览器中的一系列操作,比如向服务器发送请

PHP爬虫入门:如何选择合适的类库?PHP爬虫入门:如何选择合适的类库?Aug 09, 2023 pm 02:52 PM

PHP爬虫入门:如何选择合适的类库?随着互联网的快速发展,大量的数据散落在各个网站中。为了获取这些数据,我们常常需要使用爬虫来从网页中提取信息。而PHP作为一种常用的网页开发语言,也有许多适用于爬虫的类库可供选择。然而,在选择适合自己项目需求的类库时,我们需要考虑一些关键因素。功能丰富性:不同的爬虫类库提供了不同的功能。有些类库只能用于简单的网页抓取,而有些

PHP爬虫类的并发与多线程处理技巧PHP爬虫类的并发与多线程处理技巧Aug 08, 2023 pm 02:31 PM

PHP爬虫类的并发与多线程处理技巧引言:随着互联网的快速发展,大量的数据信息存储在各种网站上,获取这些数据已经成为很多业务场景下的需求。而爬虫作为一种自动化获取网络信息的工具,被广泛应用于数据采集、搜索引擎、舆情分析等领域。本文将介绍一种基于PHP的爬虫类的并发与多线程处理技巧,并通过代码示例来说明其实现方式。一、爬虫类的基本结构在实现爬虫类的并发与多线程处

PHP网络爬虫常见的反爬策略PHP网络爬虫常见的反爬策略Jun 14, 2023 pm 03:29 PM

网络爬虫是一种自动化抓取互联网信息的程序,它可以在很短的时间内获取大量的数据。然而,由于网络爬虫具有可扩展性和高效性等特点,使得许多网站担心可能会遭受爬虫攻击,因此采取了各种反爬策略。其中,PHP网络爬虫常见的反爬策略主要包括以下几种:IP限制IP限制是最常见的反爬虫技术,通过限制IP的访问,可以有效防止恶意的爬虫攻击。为了应对这种反爬策略,PHP网络爬虫可

用 PHP 爬取携讯星际争霸 2 游戏数据用 PHP 爬取携讯星际争霸 2 游戏数据Jun 13, 2023 am 09:34 AM

近年来,随着游戏行业的快速发展,众多游戏玩家开始关注游戏数据。而对于《星际争霸2》(下文简称SC2)这款游戏而言,其丰富的游戏数据无疑是吸引许多玩家的一大特色。为了更好地了解游戏情况,有不少玩家想利用编程技能获取游戏数据。而本文将介绍如何使用PHP编程语言实现爬取SC2游戏数据的过程。爬取网页在开始爬取SC2游戏数据之前,我们需要首先了解如何爬取一个网页。在

基于 PHP 的爬虫实现方法及注意事项基于 PHP 的爬虫实现方法及注意事项Jun 13, 2023 pm 06:21 PM

随着互联网的快速发展与普及,越来越多的数据需要被采集和处理。爬虫,作为一种常用的网络爬取工具,可以帮助快速访问、采集和整理网络数据。针对不同的需求,也会有多种语言实现爬虫,其中PHP也是比较流行的一种。今天,我们就来讲一讲基于PHP的爬虫实现方法及注意事项。一、PHP爬虫实现方法初学者建议使用现成的库针对初学者而言,可能需要积累一定的代码经验和网络

基于 PHP 的爬虫实现:如何对抗反爬虫策略基于 PHP 的爬虫实现:如何对抗反爬虫策略Jun 13, 2023 pm 03:20 PM

随着互联网的不断发展和普及,抓取网站数据的需求逐渐增加。为了满足这种需求,爬虫技术应运而生。PHP作为一门流行的开发语言,也被广泛应用于爬虫的开发中。但是,有些网站为了保护自己的数据和资源不能够被轻易地爬取,采取了反爬虫策略。那么,在PHP爬虫开发中,如何对抗这些反爬虫策略呢?下面我们来一探究竟。一、前置技能如果您想要开发高效的爬虫程序,您需要具备以下

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!