[scrapy-redis] 将scrapy爬虫改造成分布式爬虫 (2)
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
[scrapy-redis] 将scrapy爬虫改造成分布式爬虫 (2)的更多相关文章
- Python爬虫教程-新浪微博分布式爬虫分享
爬虫功能: 此项目实现将单机的新浪微博爬虫重构成分布式爬虫. Master机只管任务调度,不管爬数据:Slaver机只管将Request抛给Master机,需要Request的时候再从Master机拿 ...
- Scrapy框架之基于RedisSpider实现的分布式爬虫
需求:爬取的是基于文字的网易新闻数据(国内.国际.军事.航空). 基于Scrapy框架代码实现数据爬取后,再将当前项目修改为基于RedisSpider的分布式爬虫形式. 一.基于Scrapy框架数据爬 ...
- 【Python3爬虫】学习分布式爬虫第一步--Redis分布式爬虫初体验
一.写在前面 之前写的爬虫都是单机爬虫,还没有尝试过分布式爬虫,这次就是一个分布式爬虫的初体验.所谓分布式爬虫,就是要用多台电脑同时爬取数据,相比于单机爬虫,分布式爬虫的爬取速度更快,也能更好地应对I ...
- 基于Python,scrapy,redis的分布式爬虫实现框架
原文 http://www.xgezhang.com/python_scrapy_redis_crawler.html 爬虫技术,无论是在学术领域,还是在工程领域,都扮演者非常重要的角色.相比于其他 ...
- scrapy分布式爬虫scrapy_redis二篇
=============================================================== Scrapy-Redis分布式爬虫框架 ================ ...
- Python分布式爬虫必学框架Scrapy打造搜索引擎
Python分布式爬虫必学框架Scrapy打造搜索引擎 部分课程截图: 点击链接或搜索QQ号直接加群获取其它资料: 链接:https://pan.baidu.com/s/1-wHr4dTAxfd51M ...
- 爬虫07 /scrapy图片爬取、中间件、selenium在scrapy中的应用、CrawlSpider、分布式、增量式
爬虫07 /scrapy图片爬取.中间件.selenium在scrapy中的应用.CrawlSpider.分布式.增量式 目录 爬虫07 /scrapy图片爬取.中间件.selenium在scrapy ...
- 基于scrapy框架的分布式爬虫
分布式 概念:可以使用多台电脑组件一个分布式机群,让其执行同一组程序,对同一组网络资源进行联合爬取. 原生的scrapy是无法实现分布式 调度器无法被共享 管道无法被共享 基于 scrapy+redi ...
- 聚焦Python分布式爬虫必学框架Scrapy 打造搜索引擎视频教程
下载链接:https://www.yinxiangit.com/595.html 目录: 第1章 课程介绍介绍课程目标.通过课程能学习到的内容.和系统开发前需要具备的知识 第2章 windows下搭建 ...
随机推荐
- 【HDU5409】CRB and Graph 边双联通 子树最值
HDU # 题意 有一个简单图,n个点,m条边.对于每条割边,求出删去这条边后,在两个联通块中各取一个u,v.使得u<v,并且u尽量大而v尽量小. # 思路 求出边双联通是肯定的. 答案的限制条 ...
- P3355 骑士共存问题 二分建图 + 当前弧优化dinic
P3355 骑士共存问题 题意: 也是一个棋盘,规则是“马”不能相互打到. 思路: 奇偶点分开,二分图建图,这道题要注意每个点可以跑八个方向,两边都可以跑,所以边 = 20 * n * n. 然后di ...
- 牛客网暑期ACM多校训练营(第三场) E Sort String 哈希处理字符串(模板)
链接:https://www.nowcoder.com/acm/contest/141/E来源:牛客网 Eddy likes to play with string which is a sequen ...
- uva 796 C - Critical Links(tarjan求桥)
题目链接:https://vjudge.net/contest/67418#problem/C 题意:求出桥的个数并且按顺序输出 题解:所谓桥就是去掉这条边后连通块增加,套用一下模版就行. #incl ...
- 2017 省赛选拨 火车入站 CSU 1757 模拟
1757: 火车入站 Submit Page Summary Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 512 ...
- Python爬虫之小试牛刀——使用Python抓取百度街景图像
之前用.Net做过一些自动化爬虫程序,听大牛们说使用python来写爬虫更便捷,按捺不住抽空试了一把,使用Python抓取百度街景影像. 这两天,武汉迎来了一个德国总理默克尔这位大人物,又刷了一把武汉 ...
- Disruptor框架中生产者、消费者的各种复杂依赖场景下的使用总结
版权声明:原创作品,谢绝转载!否则将追究法律责任. Disruptor是一个优秀的并发框架,可以实现单个或多个生产者生产消息,单个或多个消费者消息,且消费者之间可以存在消费消息的依赖关系.网上其他博客 ...
- springboot使用jdbcTemplate连接数据库
springboot使用jdbcTemplate连接数据库 1.pom.xml: <?xml version="1.0" encoding="UTF-8" ...
- JavaBean的学习
一.什么是JavaBean JavaBean是一个遵循特定写法的Java类,它通常具有如下特点: 这个Java类必须具有一个无参的构造函数 属性必须私有化. 私有化的属性必须通过public类型的方法 ...
- JavaScrpt 介绍
什么是 JavaScript? JavaScript 是一种直译式脚本语言,一种轻量级的脚本语言 什么是脚本语言? Script language指的是它不具备开发操作系统的能力,而是只用来编写控制其 ...