1. 修改redis设置

redis默认处在protection mode, 修改/etc/redis.conf, protected-mode no, 或者给redis设置密码,

bind 127.0.0.1这一行用#注释掉

2. 修改爬虫设置

settings.py加入以下设置

REDIS_URL 为master的ip加上redis的端口号

# For scrapy_redis

# Enables scheduling storing requests queue in redis.
SCHEDULER = "scrapy_redis.scheduler.Scheduler" # Ensure all spiders share same duplicates filter through redis.
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # Don't cleanup redis queues, allows to pause/resume crawls.
SCHEDULER_PERSIST = True # Schedule requests using a priority queue. (default)
SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue' # Store scraped item in redis for post-processing.
ITEM_PIPELINES = {
'scrapy_redis.pipelines.RedisPipeline': 300
} # Specify the host and port to use when connecting to Redis (optional).
#REDIS_HOST = 'localhost'
#REDIS_PORT = 6379 # Specify the full Redis URL for connecting (optional).
# If set, this takes precedence over the REDIS_HOST and REDIS_PORT settings.
#REDIS_URL = 'redis://user:pass@hostname:9001'
REDIS_URL = 'redis://192.168.1.20:6379' #修改成自己的ip和port

3. 修改爬虫代码

  • 使爬虫继承自RedisSpider
from scrapy_redis.spiders import RedisSpider

class DoubanSpider(RedisSpider):
  • 增加一个redis_key属性,这个属性就是start_urls在redis中的key
  • 注释掉start_urls
#!/usr/bin/python3
# -*- coding: utf-8 -*- import scrapy
from scrapy import Request
from project_douban.items import Movie from scrapy_redis.spiders import RedisSpider class DoubanSpider(RedisSpider):
name = 'douban' allowed_domains = ['douban.com'] redis_key = "doubanSpider:start_urls" #start_urls = ['https://movie.douban.com/top250'] headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
'User-Agent' : 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Mobile Safari/537.36',
} custom_settings = {
'DEFAULT_REQUEST_HEADERS' : headers,
'REDIRECT_ENABLED' : 'False',
#'LOG_LEVEL' : 'WARNING',
} def parse(self, response):
items = response.xpath('//div[@class="item"]') for item in items:
movie = Movie()
movie['index'] = item.xpath('div//em/text()').extract_first(default = '')
self.logger.info(movie['index']) movie['src'] = item.xpath('div//img/@src').extract_first(default = '')
self.logger.info(movie['src']) movie['title'] = item.xpath('.//div[@class="hd"]/a/span[1]/text()').extract_first(default = '') #.xpath('string(.)').extract()).replace(' ','').replace('\xa0',' ').replace('\n',' ')
self.logger.info(movie['title']) movie['star'] = item.xpath('.//span[@class="rating_num"]/text()').extract_first(default = '')
self.logger.info(movie['star']) movie['info'] = item.xpath('.//div[@class="bd"]/p').xpath('string(.)').extract_first(default = '').strip().replace(' ','').replace('\xa0',' ').replace('\n',' ')
self.logger.info(movie['info']) yield movie next_url = response.xpath('//span[@class="next"]/a/@href').extract_first(default = '')
self.logger.info('next_url: ' + next_url)
if next_url:
next_url = 'https://movie.douban.com/top250' + next_url
yield Request(next_url, headers = self.headers)
  • log写入文件(optional)
import logging
import os
import time def get_logger(name, start_time = time.strftime('%Y_%m_%d_%H', time.localtime())):
path = '/var/log/scrapy-redis/'
# path = 'baidu_tieba.log'
if not os.path.exists(path):
os.makedirs(path)
log_path = path + start_time # 创建一个logger
my_logger = logging.getLogger(name)
my_logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(filename)s[line:%(lineno)d] %(message)s', datefmt = '%Y-%m-%d %H:%M:%S') # 创建handler,用于写入日志文件
handler_info = logging.FileHandler('%s_info.log' % log_path, 'a', encoding='UTF-8')
handler_info.setLevel(logging.INFO)
handler_info.setFormatter(formatter)
my_logger.addHandler(handler_info) handler_warning = logging.FileHandler('%s_warning.log' % log_path, 'a', encoding='UTF-8')
handler_warning.setLevel(logging.WARNING)
handler_warning.setFormatter(formatter)
my_logger.addHandler(handler_warning) handler_error = logging.FileHandler('%s_error.log' % log_path, 'a', encoding='UTF-8')
handler_error.setLevel(logging.ERROR)
handler_error.setFormatter(formatter)
my_logger.addHandler(handler_error) return my_logger

Miscellaneous

RedisSpider vs RedisCrawlSpider

直接看源代码,上文本比较

item RedisSpider RedisCrawlSpider
REDIS_START_URLS_AS_SET default: False default: True
继承自Spider 继承自CrawlSpider

scrapy.Spider -> scrapy.CrawlSpider

scrapy.Spider是所有爬虫的基类, scrapy.CrawlSpider基于scrapy.Spider, 增加了rules, 可以设置某种规则,只爬取满足这些规则的网页, RedisCrawlSpider也继承了这一特性

Reference

  1. Scrapy基础——Spider

  2. Scrapy基础——CrawlSpider详解

  3. Scrapy自定义日志和系统日志按级别输出到不同文件

  4. Scrapy笔记07- 内置服务

  5. scrapy中logging的使用

[scrapy-redis] 将scrapy爬虫改造成分布式爬虫 (2)的更多相关文章

  1. Python爬虫教程-新浪微博分布式爬虫分享

    爬虫功能: 此项目实现将单机的新浪微博爬虫重构成分布式爬虫. Master机只管任务调度,不管爬数据:Slaver机只管将Request抛给Master机,需要Request的时候再从Master机拿 ...

  2. Scrapy框架之基于RedisSpider实现的分布式爬虫

    需求:爬取的是基于文字的网易新闻数据(国内.国际.军事.航空). 基于Scrapy框架代码实现数据爬取后,再将当前项目修改为基于RedisSpider的分布式爬虫形式. 一.基于Scrapy框架数据爬 ...

  3. 【Python3爬虫】学习分布式爬虫第一步--Redis分布式爬虫初体验

    一.写在前面 之前写的爬虫都是单机爬虫,还没有尝试过分布式爬虫,这次就是一个分布式爬虫的初体验.所谓分布式爬虫,就是要用多台电脑同时爬取数据,相比于单机爬虫,分布式爬虫的爬取速度更快,也能更好地应对I ...

  4. 基于Python,scrapy,redis的分布式爬虫实现框架

    原文  http://www.xgezhang.com/python_scrapy_redis_crawler.html 爬虫技术,无论是在学术领域,还是在工程领域,都扮演者非常重要的角色.相比于其他 ...

  5. scrapy分布式爬虫scrapy_redis二篇

    =============================================================== Scrapy-Redis分布式爬虫框架 ================ ...

  6. Python分布式爬虫必学框架Scrapy打造搜索引擎

    Python分布式爬虫必学框架Scrapy打造搜索引擎 部分课程截图: 点击链接或搜索QQ号直接加群获取其它资料: 链接:https://pan.baidu.com/s/1-wHr4dTAxfd51M ...

  7. 爬虫07 /scrapy图片爬取、中间件、selenium在scrapy中的应用、CrawlSpider、分布式、增量式

    爬虫07 /scrapy图片爬取.中间件.selenium在scrapy中的应用.CrawlSpider.分布式.增量式 目录 爬虫07 /scrapy图片爬取.中间件.selenium在scrapy ...

  8. 基于scrapy框架的分布式爬虫

    分布式 概念:可以使用多台电脑组件一个分布式机群,让其执行同一组程序,对同一组网络资源进行联合爬取. 原生的scrapy是无法实现分布式 调度器无法被共享 管道无法被共享 基于 scrapy+redi ...

  9. 聚焦Python分布式爬虫必学框架Scrapy 打造搜索引擎视频教程

    下载链接:https://www.yinxiangit.com/595.html 目录: 第1章 课程介绍介绍课程目标.通过课程能学习到的内容.和系统开发前需要具备的知识 第2章 windows下搭建 ...

随机推荐

  1. P2805 [NOI2009]植物大战僵尸 + 最大权闭合子图 X 拓扑排序

    传送门:https://www.luogu.org/problemnew/show/P2805 题意 有一个n * m的地图,你可以操纵僵尸从地图的右边向左边走,走的一些地方是有能量值的,有些地方会被 ...

  2. HDU4614Vases and Flowers 二分+线段树;

    参考:https://blog.csdn.net/ophunter_lcm/article/details/9879495   题意: 有n个花瓶,有两种操作,1.从a开始放b朵花,有花的花瓶跳过,2 ...

  3. bzoj2049 Cave 洞穴勘测 lct

    这里比上次多了几个操作. 1. make_root(u) 换根节点, 先access(u), 再splay(u),将u移动到splay树的最顶上, 现在这棵splay对于root来说 只有左子树上有东 ...

  4. CodeForces 780 E Underground Lab

    Underground Lab 题解: 如果遍历一棵树,我们可以发现最多需要走的步数也不会超过2 * n步. 所以我们选出一棵树,然后遍历一边这颗树. 然后把序列分成k块就好了. 代码: #inclu ...

  5. Atcoder F - Mirrored(思维+搜索)

    题目链接:http://arc075.contest.atcoder.jp/tasks/arc075_d 题意:求rev(N)=N+D的个数,rev表示取反.例如rev(123)=321 题解:具体看 ...

  6. webpack4.0 babel配置遇到的问题

    babel配置 babel版本升级到8.x之后发现出现了很多问题.首先需要安装 "@babel/core": "^7.1.2", "@babel/pl ...

  7. np问题(大数阶乘取模)

    转自 np问题 题目描述: LYK 喜欢研究一些比较困难的问题,比如 np 问题. 这次它又遇到一个棘手的 np 问题.问题是这个样子的:有两个数 n 和 p,求 n 的阶乘对 p 取模后的结果. L ...

  8. 【Ehcache】基础知识学习

    一.Ehcache概述 1.1 简介 1.2 Ehcache的主要特性 二.Ehcache使用介绍 2.1 Ehcache缓存过期策略 2.2 如何解决缓存与db不同步的问题. 三.Ehcache 基 ...

  9. 【Offer】[53-3] 【数组中数值和下标相等的元素】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 假设一个单调递增的数组里的每个元素都是整数并且是唯一的.请编程实现一个函数,找出数组中任意一个数值等于其下标的元素.例如,在数组{-3, ...

  10. android 端缓存清理的实现

    首先关于缓存清理,网上已经有太多的工具类,但是遗憾的是,基本上都不完善,或者说根本就不能用,而项目中又要求实现这个烂东西(其实这玩意真没一点屁用,毕竟第三方清理/杀毒软件都带这么一个功能),但是只好硬 ...