1. # -*- coding: utf-8 -*-
  2. # scrapy爬取全部知乎用户信息
  3. # 1:是否遵守robbots_txt协议改为False
  4. # 2: 加入爬取所需的headers: user-agent,authorazation
  5. # 3:确定爬取任务:即想要得到的用户信息
  6. # 4: 爬取思路解析
  7. # 整体思路:从起始大v开始,获得其关注列表和粉丝列表;解析列表,可以得到每一个用户的详细信息地址,组成每一个用户的url;
  8. # 从用户的url开始,解析用户详细信息,取到详细信息。同时又可以解析到每一个用户的关注列表和粉丝列表,循环请求。
  9. # 分步骤如下:
  10. # 4-1:找到起始大v,请求其页面,循环翻页获取其全部的关注列表,粉丝列表
  11. # 4-2:列表步骤:解析关注列表,粉丝列表,从所有列表中取得用户的url_token,组成用户url,执行用户步骤4-3
  12. # 4-3:用户步骤:解析用户url,该步骤可以获得1.该用户详细信息 2.该用户全部的关注列表与粉丝列表,返回列表步骤4-2
  13. # 4-4:同步存储item到数据库mongodb,去重设计。
  14. import json
  15. import scrapy
  16. from zhihu2.items import Zhihu2Item
  17.  
  18. class ZhihuuserSpider(scrapy.Spider):
  19. name = 'zhihuuser'
  20. allowed_domains = ['www.zhihu.com']
  21. start_urls = ['http://www.zhihu.com/']
  22. start_user = 'excited-vczh'
  23. # 一:对用户关注列表的请求构造
  24. # 用户关注列表 start_user为起始大v,followees_include为请求参数,limit为每页显示用户数,默认20,offset为页码参数,首页为0
  25. followees_url = 'https://www.zhihu.com/api/v4/members/{user}/followees?include={include}&offset={offset}&limit={limit}'
  26. followees_include = 'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics'
  27.  
  28. # 二:对用户粉丝列表的请求构造
  29. # 用户关注列表 start_user为起始大v,followees_include为请求参数,limit为每页显示用户数,默认20,offset为页码参数,首页为0
  30. followers_url = 'https://www.zhihu.com/api/v4/members/{user}/followers?include={include}&offset={offset}&limit={limit}'
  31. followers_include = 'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics'
  32.  
  33. # 三:对用户详细信息的请求构造
  34. user_url = 'https://www.zhihu.com/api/v4/members/{user}?include={include}'
  35. user_include = 'allow_message,is_followed,is_following,is_org,is_blocking,employments,answer_count,follower_count,articles_count,gender,badge[?(type=best_answerer)].topics'
  36. def start_requests(self):
  37. # 分别举列表url和用户url示例,以验证是否能够爬取
  38. # 关注列表url示例
  39. # 返回401是请求验证用户的身份,知乎的首页是要求验证用户的身份才能进入,所以需要在settings里面设置authorization
  40. # url='https://www.zhihu.com/api/v4/members/excited-vczh/followees?include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&offset=60&limit=20'
  41. # 用户详细url示例
  42. # url='https://www.zhihu.com/api/v4/members/lanfengxing?include=allow_message%2Cis_followed%2Cis_following%2Cis_org%2Cis_blocking%2Cemployments%2Canswer_count%2Cfollower_count%2Carticles_count%2Cgender%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics'
  43. # yield scrapy.Request(url, callback=self.parse)
  44. # 构造用户关注列表的请求 主要用到format方法
  45.  
  46. yield scrapy.Request(url=self.followees_url.format(user=self.start_user, include=self.followees_include, offset=0, limit=20), callback=self.parse_followees)
  47. # 构造用户粉丝列表的请求 主要用到format方法
  48. yield scrapy.Request(url=self.followers_url.format(user=self.start_user, include=self.followers_include, offset=0, limit=20),callback=self.parse_followers)
  49. # 对用户详细信息的请求构造
  50. yield scrapy.Request(url=self.user_url.format(user=self.start_user, include=self.user_include),callback=self.parse_user)
  51. # 解析关注列表
  52. def parse_followees(self, response):
  53. results = json.loads(response.text)
  54. if 'data' in results.keys():
  55. for result in results.get('data'):
  56. # 解析关注列表,得到所关注人的url_token,构造解析详细信息请求
  57. yield scrapy.Request(url=self.user_url.format(user=result.get('url_token'), include=self.user_include),callback=self.parse_user)
  58. # 构造翻页请求
  59. if 'paging' in results.keys() and results.get('paging').get('is_end')==False:
  60. next = results.get('paging').get('next')
  61. yield scrapy.Request(url=next, callback=self.parse_followees)
  62.  
  63. # 解析粉丝列表
  64. def parse_followers(self, response):
  65. results = json.loads(response.text)
  66. if 'data' in results.keys():
  67. for result in results.get('data'):
  68. # 解析关注列表,得到所关注人的url_token,构造解析详细信息请求
  69. yield scrapy.Request(url=self.user_url.format(user=result.get('url_token'), include=self.user_include),
  70. callback=self.parse_user)
  71. # 构造翻页请求
  72. if 'paging' in results.keys() and results.get('paging').get('is_end') == False:
  73. next = results.get('paging').get('next')
  74. yield scrapy.Request(url=next, callback=self.parse_followers)
  75.  
  76. # 解析用户详细信息,由于我们任务的目标是获取用户详细信息,因此在这一步要确定哪些信息是被使用,在items里面做相应设置
  77. def parse_user(self, response):
  78. item = Zhihu2Item()
  79. # 返回的response是json格式,因此需要解析json
  80. results = json.loads(response.text)
  81. # 遍历item数据结构的键名,item.field可以得到数据结构的所有键
  82. for field in item.fields:
  83. # 如果item的键名在网页里面,则遍历赋值
  84. if field in results.keys():
  85. item[field]=results.get(field)
  86. yield item
  87.  
  88. # 提取用户的关注列表
  89. yield scrapy.Request(url=self.followees_url.format(user=results.get('url_token'),include = self.followees_include,offset=0, limit=20),callback=self.parse_followees)
  90. # 提取用户的粉丝列表
  91. yield scrapy.Request(url=self.followers_url.format(user=results.get('url_token'), include=self.followers_include, offset=0, limit=20),callback=self.parse_followers)
  1. # -*- coding: utf-8 -*-
  2.  
  3. # Define here the models for your scraped items
  4. #
  5. # See documentation in:
  6. # http://doc.scrapy.org/en/latest/topics/items.html
  7.  
  8. import scrapy
  9.  
  10. # 想要获取的用户信息设置
  11. class Zhihu2Item(scrapy.Item):
  12. # define the fields for your item here like:
  13. # name = scrapy.Field()
  14.  
  15. # 姓名 
  16. name = scrapy.Field()
  17. # 性别
  18. gender = scrapy.Field()
  19. # 职业
  20. employments = scrapy.Field()
  21. # 级别
  22. badge = scrapy.Field()
  23. # 一句话介绍
  24. headline = scrapy.Field()
  25. # 粉丝数
  26. follower_count = scrapy.Field()
  27. # 回答问题数
  28. answer_count = scrapy.Field()
  29. # 撰写文章数
  30. articles_count = scrapy.Field()
  31. # 头像
  32. avatar_url = scrapy.Field()
  33. avatar_url_template = scrapy.Field()
  34. # id
  35. id = scrapy.Field()
  36. # 注册类型
  37. type = scrapy.Field()
  38. # 注册url
  39. url = scrapy.Field()
  40. # 主页地址,唯一识别码
  41. url_token = scrapy.Field()
  42. # 用户类型
  43. user_type = scrapy.Field()
  1. # -*- coding: utf-8 -*-
  2.  
  3. # Define your item pipelines here
  4. #
  5. # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  6. # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
  7. import pymongo
  8. # 项目管道用来处理得到的item信息,这里设置存储到MongoDB的class
  9. class MongoPipeline(object):
  10.  
  11. #初始化变量, 这里需要传入mongo_uri,mongo_db两个参数,这两个参数可以从类方法里面获得
  12. def __init__(self,mongo_uri,mongo_db):
  13. self.mongo_uri = mongo_uri
  14. self.mongo_db = mongo_db
  15.  
  16. # 定义类方法,获得mongo_uri,mongo_db
  17. @classmethod
  18. def from_crawler(cls,crawler):
  19. return cls(
  20. mongo_uri = crawler.settings.get('MONGO_URI'),
  21. mongo_db = crawler.settings.get('MONGO_DB')
  22. )
  23.  
  24. # 初始化mongodb的变量,client, 与db,爬虫启动时即开始初始化
  25. def open_spider(self,spider):
  26. self.client = pymongo.MongoClient(self.mongo_uri)
  27. self.db = self.client[self.mongo_db]
  28.  
  29. # 存储主体进程,返回item或者DropItem,这里设置update方法设置去重, 如果有同名就更新,没有就重新建立
  30. def process_item(self, item, spider):
  31. name = item.__class__.__name__
  32. self.db[name].update({'url_token':item['url_token']}, {'$set':item}, True)
  33. return item
  34.  
  35. # 关闭mongodb
  36. def close_spider(self,spider):
  37. self.client.close()
  1. # -*- coding: utf-8 -*-
  2.  
  3. # Scrapy settings for zhihu2 project
  4. #
  5. # For simplicity, this file contains only settings considered important or
  6. # commonly used. You can find more settings consulting the documentation:
  7. #
  8. # http://doc.scrapy.org/en/latest/topics/settings.html
  9. # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
  10. # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
  11.  
  12. BOT_NAME = 'zhihu2'
  13.  
  14. SPIDER_MODULES = ['zhihu2.spiders']
  15. NEWSPIDER_MODULE = 'zhihu2.spiders'
  16.  
  17. MONGO_URI = 'localhost'
  18. MONGO_DB = 'zhihu2'
  19. # Crawl responsibly by identifying yourself (and your website) on the user-agent
  20. #USER_AGENT = 'zhihu2 (+http://www.yourdomain.com)'
  21.  
  22. # Obey robots.txt rules
  23. ROBOTSTXT_OBEY = False
  24.  
  25. # Configure maximum concurrent requests performed by Scrapy (default: 16)
  26. #CONCURRENT_REQUESTS = 32
  27.  
  28. # Configure a delay for requests for the same website (default: 0)
  29. # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
  30. # See also autothrottle settings and docs
  31. #DOWNLOAD_DELAY = 3
  32. # The download delay setting will honor only one of:
  33. #CONCURRENT_REQUESTS_PER_DOMAIN = 16
  34. #CONCURRENT_REQUESTS_PER_IP = 16
  35.  
  36. # Disable cookies (enabled by default)
  37. #COOKIES_ENABLED = False
  38.  
  39. # Disable Telnet Console (enabled by default)
  40. #TELNETCONSOLE_ENABLED = False
  41.  
  42. # Override the default request headers:
  43.  
  44. DEFAULT_REQUEST_HEADERS = {
  45. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  46. 'Accept-Language': 'en',
  47. 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
  48. 'authorization':'oauth c3cef7c66a1843f8b3a9e6a1e3160e20',
  49. }
  50.  
  51. # Enable or disable spider middlewares
  52. # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
  53. #SPIDER_MIDDLEWARES = {
  54. # 'zhihu2.middlewares.Zhihu2SpiderMiddleware': 543,
  55. #}
  56.  
  57. # Enable or disable downloader middlewares
  58. # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
  59. #DOWNLOADER_MIDDLEWARES = {
  60. # 'zhihu2.middlewares.MyCustomDownloaderMiddleware': 543,
  61. #}
  62.  
  63. # Enable or disable extensions
  64. # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
  65. #EXTENSIONS = {
  66. # 'scrapy.extensions.telnet.TelnetConsole': None,
  67. #}
  68.  
  69. # Configure item pipelines
  70. # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
  71. ITEM_PIPELINES = {
  72. 'zhihu2.pipelines.MongoPipeline': 300,
  73. }
  74.  
  75. # Enable and configure the AutoThrottle extension (disabled by default)
  76. # See http://doc.scrapy.org/en/latest/topics/autothrottle.html
  77. #AUTOTHROTTLE_ENABLED = True
  78. # The initial download delay
  79. #AUTOTHROTTLE_START_DELAY = 5
  80. # The maximum download delay to be set in case of high latencies
  81. #AUTOTHROTTLE_MAX_DELAY = 60
  82. # The average number of requests Scrapy should be sending in parallel to
  83. # each remote server
  84. #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
  85. # Enable showing throttling stats for every response received:
  86. #AUTOTHROTTLE_DEBUG = False
  87.  
  88. # Enable and configure HTTP caching (disabled by default)
  89. # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
  90. #HTTPCACHE_ENABLED = True
  91. #HTTPCACHE_EXPIRATION_SECS = 0
  92. #HTTPCACHE_DIR = 'httpcache'
  93. #HTTPCACHE_IGNORE_HTTP_CODES = []
  94. #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

scrapy爬取全部知乎用户信息的更多相关文章

  1. Python爬虫从入门到放弃(十八)之 Scrapy爬取所有知乎用户信息(上)

    爬取的思路 首先我们应该找到一个账号,这个账号被关注的人和关注的人都相对比较多的,就是下图中金字塔顶端的人,然后通过爬取这个账号的信息后,再爬取他关注的人和被关注的人的账号信息,然后爬取被关注人的账号 ...

  2. Python之爬虫(二十) Scrapy爬取所有知乎用户信息(上)

    爬取的思路 首先我们应该找到一个账号,这个账号被关注的人和关注的人都相对比较多的,就是下图中金字塔顶端的人,然后通过爬取这个账号的信息后,再爬取他关注的人和被关注的人的账号信息,然后爬取被关注人的账号 ...

  3. Python爬虫从入门到放弃(十九)之 Scrapy爬取所有知乎用户信息(下)

    在上一篇文章中主要写了关于爬虫过程的分析,下面是代码的实现,完整代码在:https://github.com/pythonsite/spider items中的代码主要是我们要爬取的字段的定义 cla ...

  4. Python之爬虫(二十一) Scrapy爬取所有知乎用户信息(下)

    在上一篇文章中主要写了关于爬虫过程的分析,下面是代码的实现,完整代码在:https://github.com/pythonsite/spider items中的代码主要是我们要爬取的字段的定义 cla ...

  5. 利用Scrapy爬取所有知乎用户详细信息并存至MongoDB

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者 :崔庆才 本节分享一下爬取知乎用户所有用户信息的 Scrapy 爬虫实战. 本节目标 本节要实现的内容有 ...

  6. 使用 Scrapy 爬取去哪儿网景区信息

    Scrapy 是一个使用 Python 语言开发,为了爬取网站数据,提取结构性数据而编写的应用框架,它用途广泛,比如:数据挖掘.监测和自动化测试.安装使用终端命令 pip install Scrapy ...

  7. 利用scrapy爬取腾讯的招聘信息

    利用scrapy框架抓取腾讯的招聘信息,爬取地址为:https://hr.tencent.com/position.php 抓取字段包括:招聘岗位,人数,工作地点,发布时间,及具体的工作要求和工作任务 ...

  8. 抓取百万知乎用户信息之HttpHelper的迭代之路

    什么是Httphelper? httpelpers是一个封装好拿来获取网络上资源的工具类.因为是用http协议,故取名httphelper. httphelper出现的背景 使用WebClient可以 ...

  9. 43.scrapy爬取链家网站二手房信息-1

    首先分析:目的:采集链家网站二手房数据1.先分析一下二手房主界面信息,显示情况如下: url = https://gz.lianjia.com/ershoufang/pg1/显示总数据量为27589套 ...

随机推荐

  1. 【Java】 重拾Java入门

    [概论与基本语法] 取这个标题,还是感觉有些大言不惭.之前大三的时候自学过一些基本的java知识,大概到了能独立写一个GUI出来的水平把,不过后来随着有了其他目标,就把这块放下了.之后常年没有用,早就 ...

  2. CSS以及JQuery总是忽略掉的小问题

    1.自动居中一列布局需要设置 margin 左右值设置为 auto,而且一定要设置width为一个定值. 2.css3: 3.修改时间SQL(格式) update table set timeColu ...

  3. java.lang.Thread、java.lang.ThreadGroup和java.lang.ThreadLocal<T>详细解读

    一.Thread类 public class Thread extends Object  impments Runnable 线程是程序中的 执行线程.java虚拟机允许应用程序并发地运行多个执行线 ...

  4. Laravel 中缓存驱动的速度比较

    缓存是web开发中重要的一部分,我相信很多人和我一样,经常忽略这个问题. 随着工作经验的累积,我已经意识到缓存是多么的重要,这里我通过 Scotch 来解释一下它的重要性. 通过观察发现,Scotch ...

  5. virtualbox主机与虚拟机之间互相通信教程

    前言 在使用虚拟机搭建集群时,需要实现虚拟机与虚拟机之间互相ping通,并且主机与虚拟机也可以互相ping通. 一.环境准备: 1.主机为win7 2.virtualbox下创建两台ubuntu虚拟机 ...

  6. 大数据hadoop面试题2018年最新版(美团)

    还在用着以前的大数据Hadoop面试题去美团面试吗?互联网发展迅速的今天,如果不及时更新自己的技术库那如何才能在众多的竞争者中脱颖而出呢? 奉行着"吃喝玩乐全都有"和"美 ...

  7. hibernate框架学习笔记11:Criteria查询详解

    创建实体类对象: package domain; import java.util.HashSet; import java.util.Set; //客户实体 public class Custome ...

  8. DES MEI号码加密

    对于加密来说,使用DES加密解密很好,但是为了使不同设备的密文不一样,可以使用 固定字符串 + 设备IMEI号码 加密的方式,这样可以分辨不同手机,限制手机的使用(若是注册,一个手机只有一个IMEI号 ...

  9. RAID6三块硬盘离线导致的数据丢失恢复过程

    小编我最近参与了一例非常成功的数据恢复的案例,在这里分享给大家.用户是一组6块750G磁盘的 RAID6,先后有两块磁盘离线,但维护人员在此情况下依然没有更换磁盘,所以在第三块硬盘离线后raid直接崩 ...

  10. 更优雅的方式: JavaScript 中顺序执行异步函数

    火于异步 1995年,当时最流行的浏览器--网景中开始运行 JavaScript (最初称为 LiveScript). 1996年,微软发布了 JScript 兼容 JavaScript.随着网景.微 ...