scrapy限速配置

来源:8-5 通过downloadmiddleware随机更换user-agent - 2

慕尼黑530398

2017-12-28

老师好,请教个问题。我在一个服务器上部署爬虫,有20个可用的IP。想开20个并发,每个request都有一个自己的IP。现在想对这20个request分别做限速。这么才能做到呢? 


写回答

2回答

慕尼黑530398

提问者

2017-12-31

我做了这么一个中间件,貌似能实现这个功能,但是不能调试,也不知会有什么隐患,老师帮忙看一下。


import random
import gevent, time

from scrapy import signals
from gevent.queue import JoinableQueue
from gevent import monkey


class GeventPoolExecutor(object):
  def __init__(self, max_works):
     self._q = JoinableQueue()
     self.count = 0

     for i in range(max_works):
        gevent.spawn(self.worker)
     self._q.join()

  def worker(self):
     while True:
        fn = self._q.get()
        try:
           exec(fn)
        except Exception as e:
           print(e)
        finally:
           self._q.task_done()

  def submit(self, fn):
     self._q.put(fn)

  def func(self):
     self.count += 1
     count = self.count
     print('阻塞函数%s' % count,os.getpid())
     block_time = random.randint(1, 4)
     time.sleep(block_time)
     print('阻塞完成%s' % count, '阻塞时间%s' % block_time)


class DelayMiddlware(object):
  # 随机针对每次请求延时
  def __init__(self, ):
     super(DelayMiddlware, self).__init__()
     self.gevent_pool_executor = GeventPoolExecutor(max_works=1000)

0
3
bobby
回复
慕尼黑530398
在linux下面也有报错 不报错的话就不用安装了
2018-01-05
共3条回复

bobby

2017-12-29

要做到这个需要自己去修改一些源码才行 目前scrapy还没有针对具体某个request限速的方法

0
0

Scrapy打造搜索引擎 畅销4年的Python分布式爬虫课

带你彻底掌握Scrapy,用Django+Elasticsearch搭建搜索引擎

5763 学习 · 6266 问题

查看课程