基于scrapy-redis的第二种形式的分布式爬虫(把普通scrapy框架转成分布式)
1.基于RedisSpider实现的分布式爬虫(网易新闻)
a) 代码修改(爬虫类):
i.导包: from scrapy_redis.spiders import RedisSpider
ii. 将爬虫类的父类修改成RedisSpider
iii. 将起始url列表注释,添加一个redis_key(调度器队列的名称)的属性
b) redis 数据库配置文件的配置redisxxx.conf:
i. #bind 127.0.0.1
ii. protected-mode no
c) 对项目中settings进行配置
i
#配置redis服务的ip和端口 REDIS_HOST = 'redis服务的ip地址' REDIS_PORT = 6379 #REDIS_PARAMS = {'password': '123456'}
ii
#使用scrapy-redis组件的去重队列 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" #使用scrapy-redis组件自己的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" #是否允许暂停 SCHEDULER_PERSIST = True
iii 使用可以被共享的管道
ITEM_PIPELINES={ 'scrapy_redis.pipelines.RedisPipeline': 400, }
d) 开启redis数据库的服务:redis-server配置文件
e) 执行爬虫文件:scrapy runspider wangyi.py
f) 向调度器的管道中扔一个起始的url:
i. 开启redis客户端
ii. 向调度器队列中扔一个起始url
lpush wangyi https://xxxx.com # wangyi为 scrapy_redis的名字
2.UA池(在settings里加上该中间件方法)
a) 在中间价类中进行导包
from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
b)封装一个基于UserAgentMiddleware的类,且重写该类
例:
middleware.py
from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware import random ua_list = ['Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50', 'User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50', 'User-Agent:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;', 'User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)', 'User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)', 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', 'User-Agent:Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', 'User-Agent:Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11'] ip_http_list = ['90.229.216.218:46796', '110.235.250.7:49341', '81.163.62.136:41258', '195.34.207.47:60878'] ip_https_list = ['140.227.207.211:60088', '140.227.209.210:60088', '185.132.133.102:1080'] class UserAgentRandom(UserAgentMiddleware): def process_request(self, request, spider): ua = random.choice(ua_list) request.headers.setdefault('User-Agent', ua)
settings.py
DOWNLOADER_MIDDLEWARES = { 'handle5.middlewares.Handle5DownloaderMiddleware': 543, 'handle5.middlewares.UserAgentRandom': 542, 'handle5.middlewares.IpRandom': 541 }
3.代理池(IP)(在settings里加上该中间件方法)
修改ip
middleware.py(与上述代码补全整个页面)
class IpRandom: def process_request(self, request, spider): url = request.url head = url.split(":")[0] if head == "http": request.meta["proxy"] = "http://" + random.choice(ip_http_list) else: request.meta["proxy"] = "https://" + random.choice(ip_https_list)
4.selenium如何被应用到scrapy 中
a) 在爬虫文件中导入webdriver类
b) 在爬虫文件的爬虫类的构造方法中进行了浏览器的实例化操作
c) 在爬虫类的closed方法中进行浏览器关闭的操作
d) 在下载中间件的process_response 方法中编写执行浏览器自动化的操作