6

是否可以延迟特定scrapy请求的重试。我有一个中间件需要将页面请求推迟到以后。我知道如何进行基本的延迟(队列结束),以及如何延迟所有请求(全局设置),但我只想延迟这个单独的请求。这在队列末尾附近最重要,如果我执行简单的延迟,它会立即再次成为下一个请求。

4

3 回答 3

3

方法一

一种方法是向您的 Spider 添加一个中间件(sourcelinked):

# File: middlewares.py

from twisted.internet import reactor
from twisted.internet.defer import Deferred


class DelayedRequestsMiddleware(object):
    def process_request(self, request, spider):
        delay_s = request.meta.get('delay_request_by', None)
        if not delay_s:
            return

        deferred = Deferred()
        reactor.callLater(delay_s, deferred.callback, None)
        return deferred

你以后可以像这样在你的蜘蛛中使用它:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    custom_settings = {
        'DOWNLOADER_MIDDLEWARES': {'middlewares.DelayedRequestsMiddleware': 123},
    }

    def start_requests(self):
        # This request will have itself delayed by 5 seconds
        yield scrapy.Request(url='http://quotes.toscrape.com/page/1/', 
                             meta={'delay_request_by': 5})
        # This request will not be delayed
        yield scrapy.Request(url='http://quotes.toscrape.com/page/2/')

    def parse(self, response):
        ...  # Process results here

方法二

您可以使用自定义重试中间件(source)来做到这一点,您只需要覆盖process_response当前重试中间件的方法:

from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message


class CustomRetryMiddleware(RetryMiddleware):

    def process_response(self, request, response, spider):
        if request.meta.get('dont_retry', False):
            return response
        if response.status in self.retry_http_codes:
            reason = response_status_message(response.status)

            # Your delay code here, for example sleep(10) or polling server until it is alive

            return self._retry(request, reason, spider) or response

        return response

然后启用它而不是默认RetryMiddlewaresettings.py

DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.retry.RetryMiddleware': None,
    'myproject.middlewarefilepath.CustomRetryMiddleware': 550,
}
于 2020-11-19T00:28:53.850 回答
-1

使用的解决方案twisted.reactor.callLater()在这里:

https://github.com/ArturGaspar/scrapy-delayed-requests

于 2019-06-04T16:44:14.780 回答
-2

sleep() 方法在给定的秒数内暂停执行。该参数可以是一个浮点数,以指示更精确的睡眠时间。

所以你必须在你的蜘蛛中导入时间模块。

import time

然后你可以在需要延迟的地方添加 sleep 方法。

time.sleep( 5 )
于 2014-10-07T04:51:53.837 回答