16.2 知乎爬虫的实现
16.2.1 编写知乎爬虫代码
通过上节分析,我们知道使用 Scrapy 的 CrawlSpider 根据 URL 规则爬取是一个非常好的策略,它可以使爬虫代码非常简洁。下面开始编写代码。
第一步,生成项目,并使用 crawl 模板生成 spider。
scrapy startproject pachong6 cd pachong6 scrapy genspider -t crawl zhihu zhihu.com
第二步,根据需要提取的数据,定义 Item。
class Pachong6Item(scrapy.Item):
name = scrapy.Field() #姓名(昵称)
intro = scrapy.Field() #一句话介绍
detail = scrapy.Field() #详细资料
following = scrapy.Field() #关注的对象数
followers = scrapy.Field() #粉丝数 第三步,根据上节的分析,编写 spider,定义链接提取规则。
class ZhihuSpider(CrawlSpider):
name = 'zhihu'
allowed_domains = ['zhihu.com']
#使用李开复老师的个人页面作为 start_urls
start_urls = ['https://www.zhihu.com/people/kaifulee/activities']
rules = (
Rule(LinkExtractor(allow=(['people/.*/following$',
'people/.*/followers$']), )),
Rule(LinkExtractor(allow=('www.zhihu.com/people/((?!/).)*$', )),
callback='parse_item', follow=True),)第四步,定义个人页面的解析函数。
def parse_item(self, response):
item = Pachong6Item()
item['name'] = response.xpath(
"//*[@class='ProfileHeader-name']/text()").extract_first()
item['intro'] = response.xpath(
"//*[@class='RichText ProfileHeader-headline']/text()").extract_first()
item['detail'] = response.xpath(
"string(//*[@class='ProfileHeader-info'])").extract_first()
follow_list = response.xpath(
"//*[@class='NumberBoard-itemValue']/text()").extract()
if follow_list:
item['following'] = follow_list[0]
item['followers'] = follow_list[1]
return item 这里为了避免在爬取到需要登录才能查看其个人页面的用户时报错,对 follow_list 先判断是否为空,不为空的话再取出关注的人数和粉丝数。而前面的 intro 项和 detail 项都是使用 extract_first 方法序列化数据,没有数据时直接返回 None,不会报错。
第五步,设置 settings.py。
为了防止被知乎服务器反爬虫禁止,需要在设置文件中设置 User Agent、增加下载延时并停止 Cookies。
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' ROBOTSTXT_OBEY = False DOWNLOAD_DELAY = 5 COOKIES_ENABLED = False
至此就完成了爬虫部分的代码编写。这里仅仅使用这二十多行的代码就编写了一个知乎用户数据爬虫,可以直接使用 Scrapy 的 feed 快捷保存方式运行爬虫。
16.2.2 使用 MongoDB 和 scrapy_redis 搭建分布式爬虫
要使用 MongoDB 存储爬取数据,需要在 pipeline 中编写相关代码。
import pymongo
from pymongo import MongoClient
class Pachong6Pipeline(object):
#在 open_spider 方法中链接 MongoDB,创建数据库
#和集合
def open_spider(self, spider):
self.db = MongoClient('localhost', 27017)
self.collection = slef.db.zhihu_collection
#定义 process_item 方法
def process_item(self, item, spider):
self.collection.insert_one(dict(item))
#在 spider 关闭的同时关闭连接
def close_spider(self, spider):
self.collection.close() 这里使用 process_item 将转换成字典的 Item 数据保存到了 MongoDB 中。千万不要忘记,还需要在 settings 中启用 pipeline。
ITEM_PIPELINES = {
'pachong6.pipelines.Pachong6Pipeline': 300,
} 要搭建分布式爬虫,需要在 settings.py 中配置使用 scrapy_redis 作为调度器。
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
设置使用 scrapy_redis 去重。
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
设置 Redis 的连接信息。
REDIS_URL = 'redis://localhost:6379'
设置 Redis 队列为保存。
SCHEDULER_PERSIST = True
最后,修改 spider 为从 scrapy_redis.spiders.RedisCrawlSpider 类继承。
from scrapy_redis.spiders import RedisCrawlSpider
class ZhihuSpider(RedisCrawlSpider):
name = 'zhihu'
allowed_domains = ['zhihu.com']
redis_key = 'ZhihuSpider:start_urls'
#其他内容不变
...这样就实现了一个简单的知乎用户数据爬虫。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论