【问题标题】:Add a delay after 500 requests scrapy在 500 个请求后添加延迟
【发布时间】:2016-07-31 20:57:30
【问题描述】:

我有一个起始 2000 网址的列表,我正在使用:

DOWNLOAD_DELAY = 0.25 

为了控制请求的速度,但我还想在 n 个请求之后添加更大的延迟。 例如,我希望每个请求延迟 0.25 秒,每 500 个请求延迟 100 秒。

编辑:

示例代码:

import os
from os.path import join
import scrapy
import time

date = time.strftime("%d/%m/%Y").replace('/','_')

list_of_pages = {'http://www.lapatilla.com/site/':'la_patilla',                 
                 'http://runrun.es/':'runrunes',
                 'http://www.noticierodigital.com/':'noticiero_digital',
                 'http://www.eluniversal.com/':'el_universal',
                 'http://www.el-nacional.com/':'el_nacional',
                 'http://globovision.com/':'globovision',
                 'http://www.talcualdigital.com/':'talcualdigital',
                 'http://www.maduradas.com/':'maduradas',
                 'http://laiguana.tv/':'laiguana',
                 'http://www.aporrea.org/':'aporrea'}

root_dir = os.getcwd()
output_dir = join(root_dir,'data/',date)

class TestSpider(scrapy.Spider):
    name = "news_spider"
    download_delay = 1

    start_urls = list_of_pages.keys()

    def parse(self, response):
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        filename =   list_of_pages[response.url]
        print time.time()
        with open(join(output_dir,filename), 'wb') as f:
            f.write(response.body)

在这种情况下,列表更短,但想法是相同的。我希望每个请求一个延迟级别,每个“N”个请求一个延迟级别。 我没有抓取链接,只是保存主页。

【问题讨论】:

  • 在这方面帮助您需要更多代码。
  • 如果您需要一些好的方法方面的帮助,请发帖minimal reproducible example,否则这个问题对于 SO 来说太宽泛了
  • @DavidGomes 添加代码
  • @WayneWerner 代码添加

标签: python web-scraping scrapy


【解决方案1】:

您可以考虑使用AutoThrottle extension,它不会让您严格控制延迟,而是有自己的算法来减慢蜘蛛的速度,根据响应时间和并发请求的数量动态调整它。

如果您需要更好地控制抓取过程某些阶段的延迟,您可能需要custom middleware 或自定义扩展(类似于 AutoThrottle - source)。

您还可以即时更改.download_delay attribute of your spider。顺便说一句,这正是 AutoThrottle 扩展在幕后所做的——updates the .download_delay value on the fly

一些相关的话题:

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2022-08-18
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2019-02-13
    • 2021-01-08
    相关资源
    最近更新 更多