-
Notifications
You must be signed in to change notification settings - Fork 0
/
middlewares.py
executable file
·56 lines (45 loc) · 1.63 KB
/
middlewares.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
```python
from scrapy import signals
from scrapy.exceptions import IgnoreRequest
from scrapy.http import Response
import time
class RateLimitMiddleware(object):
def __init__(self):
self.last_request_time = time.time()
def process_request(self, request, spider):
delay = 1 # Delay in seconds
elapsed_time = time.time() - self.last_request_time
if elapsed_time < delay:
time.sleep(delay - elapsed_time)
self.last_request_time = time.time()
class ErrorHandlingMiddleware(object):
def process_exception(self, request, exception, spider):
if isinstance(exception, IgnoreRequest):
return Response(request.url, status=200, body='')
class CachingMiddleware(object):
def __init__(self):
self.cache = {}
def process_request(self, request, spider):
if request.url in self.cache:
return self.cache[request.url]
else:
return None
def process_response(self, request, response, spider):
self.cache[request.url] = response
return response
class WebScraperSpiderMiddleware(object):
@classmethod
def from_crawler(cls, crawler):
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
return None
def process_spider_output(self, response, result, spider):
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
```