Повторите запрос в промежуточном программном обеспечении загрузчика scrapy - PullRequest
0 голосов
/ 05 февраля 2020

Я использую 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)



1 Ответ

0 голосов
/ 06 февраля 2020

Вместо того, чтобы возвращать новый объект запроса, вы должны скопировать исходный запрос как retry = request.copy(). Вы можете проверить, как Scrapy's RetryMiddleware обрабатывает попытки .

Для справки:

def _retry(self, request):
    ...
    retryreq = request.copy()
    retryreq.dont_filter = True
    ...
    return retryreq

И вы можете назвать это как

def process_response(self, request, response, spider):
    try:
        if response.status in self._http_status_codes:
            name = response.headers['x-cache-proxyname'].decode('utf-8')
            self._stop_and_sleep(spider, name)
            return self._retry(request)
        return response

Это должно дать вам идею.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...