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. 2019 Multi-University Training Contest 1

    2019 Multi-University Training Contest 1 A. Blank upsolved by F0_0H 题意 给序列染色,使得 \([l_i,r_i]\) 区间内恰出现 ...

  2. hdu 4513(Manacher)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4513 题解:就是在Manacher判断回文串的过程中添加一条条件 Ma[i + dp[i] - 2] ...

  3. Pipenv的简单使用

    安装 $ pip install pipenv 安装虚拟环境 pipenv install 新建一个准备当环境的文件夹pipenvtest,并cd进入该文件夹: - pipenv --three 会使 ...

  4. 卸载VMware

    最近使用ubuntu的时候操作不当直接卡死了,然后强制关闭VMware软件,之后再打开时出现本文中的 “Vmware启动ubuntu 出现错误 ”这个情况,具体请看链接:https://www.cnb ...

  5. Python二元操作符

    def quiz_message(grade): outcome = 'failed' if grade<50 else 'passid' print ('grade', grade, 'out ...

  6. Python3实战Spark大数据分析及调度 (网盘分享)

    Python3实战Spark大数据分析及调度 搜索QQ号直接加群获取其它学习资料:715301384 部分课程截图: 链接:https://pan.baidu.com/s/12VDmdhN4hr7yp ...

  7. 拒绝一次性买卖:MyBatis的mapper和repository可重复生成工具

    背景 MyBatis的历史可谓久远了,码农们也在用着各式各样的代码生成工具.然而这些工具大部分都有一个缺点,那就是只能一次性生成文件.如果我们期间在生成的文件里做了修改,再次生成时,很多工具会覆盖我们 ...

  8. 错误:java.lang.Exception: No tests found matching Method testPrePage1(egou_manager_web.TestEBrand) from org.junit.internal.requests.ClassRequest@4f3cc73c

    今天测试分页时出现以下错误: java.lang.Exception: No tests found matching Method testPrePage1(egou_manager_web.Tes ...

  9. HBase的表结构

    HBase以表的形式存储数据.表有行和列组成.列划分为若干个列族/列簇(column family).  如上图所示,key1,key2,key3是三条记录的唯一的row key值,column-fa ...

  10. HBase 超详细介绍

    1-HBase的安装 HBase是什么? HBase是Apache Hadoop中的一个子项目,Hbase依托于Hadoop的HDFS作为最基本存储基础单元,通过使用hadoop的DFS工具就可以看到 ...