Scrapy 请求+响应+下载时间

标签 scrapy

UPD : 不是很接近的问题,因为我认为我的方式并不像应该的那么清楚

是否可以获取当前请求 + 响应 + 下载时间以将其保存到 Item?

在“普通” python 我做

start_time = time()
urllib2.urlopen('http://example.com').read()
time() - start_time

但是我怎么能用 Scrapy 做到这一点呢?

UPD :

解决方案对我来说足够了,但我不确定结果的质量。如果您有许多连接超时错误 Download time可能是错误的(甚至 DOWNLOAD_TIMEOUT * 3)

为了

设置.py
DOWNLOADER_MIDDLEWARES = {
    'myscraper.middlewares.DownloadTimer': 0,
}

中间件.py
from time import time
from scrapy.http import Response


class DownloadTimer(object):
    def process_request(self, request, spider):
        request.meta['__start_time'] = time()
        # this not block middlewares which are has greater number then this
        return None

    def process_response(self, request, response, spider):
        request.meta['__end_time'] = time()
        return response  # return response coz we should

    def process_exception(self, request, exception, spider):
        request.meta['__end_time'] = time()
        return Response(
            url=request.url,
            status=110,
            request=request)

def parse(... 中的 spider.py 中
log.msg('Download time: %.2f - %.2f = %.2f' % (
    response.meta['__end_time'], response.meta['__start_time'],
    response.meta['__end_time'] - response.meta['__start_time']
), level=log.DEBUG)

最佳答案

你可以写一个 Downloader Middleware这将计时每个请求。它会在请求发出之前为请求添加一个开始时间,然后在请求完成时添加一个完成时间。通常,诸如此类的任意数据存储在 Request.meta 中。属性。此时间信息稍后可以由您的蜘蛛读取并添加到您的项目中。

这个下载器中间件听起来对很多项目都有用。

关于Scrapy 请求+响应+下载时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15831955/

相关文章:

javascript - 使用scrapy,如何抓取带有onclick属性的复选框的页面?

amazon-s3 - Scrapy 抓取在本地附加,在 S3 上替换?

python - 我如何减少这里的 try/catch 语句的数量?

python - 类型错误 : cannot concatenate 'str' and 'NoneType' objects when placing the custom url in scrapy. 请求()

Scrapy-递归抓取网页并将内容保存为html文件

python-2.7 - Scrapy CrawlSpider 不遵循特定页面上的链接

python - 使用scrapy下载图片时遇到问题

python - 碎片化 1.0 : How to run crawler in Celery?

python - 使用 subprocess.Popen 时 Scrapy ImportError : No module named project. 设置

python - 我如何跳转到 Scrapy 规则中的下一页