Я использую scrapoxy, который реализует ротацию IP при утилизации.
У меня есть список BLACKLIST_HTTP_STATUS_CODES
кодов состояния, которые указывают, что текущий IP заблокирован.
Проблема : после получения ответа с кодом состояния в BLACKLIST_HTTP_STATUS_CODES
промежуточное ПО загрузчика scrapoxy вызывает IgnoreRequest, а затем меняет IP. В результате мой скрипт пропускает URL, ответ которого получил неправильный код состояния.
Пример журналов:
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.some-website.com/profile/190> (referer: None)
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.some-website.com/profile/191> (referer: None)
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.some-website.com/profile/192> (referer: None)
[spider] DEBUG: Ignoring Blacklisted response https://www.some-website.com/profile/193: HTTP status 429
[urllib3.connectionpool] DEBUG: Starting new HTTP connection (1): 13.33.33.37:8889
[urllib3.connectionpool] DEBUG: http://13.33.33.37:8889 "POST /api/instances/stop HTTP/1.1" 200 11
[spider] DEBUG: Remove: instance removed (1 instances remaining)
[spider] INFO: Sleeping 89 seconds
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.some-website.com/profile/194> (referer: None)
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.some-website.com/profile/195> (referer: None)
[scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.some-website.com/profile/196> (referer: None)
В результате мой скрипт пропустил https://www.some-website.com/profile/193
.
Цель : я хочу повторить запрос, ответ которого получил код состояния, который находится в BLACKLIST_HTTP_STATUS_CODES
, пока его нет в этом списке.
Мой DownloaderMiddleware выглядит так :
class BlacklistDownloaderMiddleware(object):
def __init__(self, crawler):
...
def from_crawler(cls, crawler):
...
def process_response(self, request, response, spider):
"""
Detect blacklisted response and stop the instance if necessary.
"""
try:
# self._http_status_codes is actually BLACKLIST_HTTP_STATUS_CODES
if response.status in self._http_status_codes:
# I have defined BlacklistErorr
raise BlacklistError(response, 'HTTP status {}'.format(response.status))
return response
# THIS IS HOW ORIGINAL CODE LOOKS
except BlacklistError as ex:
# Some logs
spider.log('Ignoring Blacklisted response {0}: {1}'.format(response.url, ex.message), level=logging.DEBUG)
# Get the name of proxy that I need to change
name = response.headers['x-cache-proxyname'].decode('utf-8')
# Change the proxy
self._stop_and_sleep(spider, name)
# drop the url
raise IgnoreRequest()
# MY TRY: I have tried this instead of raising IgnoreRequest but
# it does not work and asks for arguments spider and
# response for self.process_response
# return Request(response.url, callback=self.process_response, dont_filter=True)