在Scrapy spider中添加暂停功能

问题描述 投票:0回答:1

嗨,我想创建蜘蛛,每天搜刮一个网站。我有一个蜘蛛,可以搜刮所有我需要的东西,但我需要实现在每篇文章搜刮后暂停。我已经尝试过 threading 模块和 time 模块,但使用它们似乎并不奏效,因为我得到了这样的响应(只从一些请求中得到)。


DEBUG: Retrying <GET https://www.example.com/.../> (failed 1 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionLost: Connection to the other side was lost in a non-clean fashion: Connection lost.>].


我的代码是这样的

class AutomatedSpider(scrapy.Spider):
    name = 'automated'
    allowed_domains = ['example-domain.com']
    start_urls = [
        'https://example.com/page/1/...'
    ]
    pause = threading.Event()
    article_num = 1

    def parse(self, response):
        for page_num in range(1, 26):
            for href in set(response.css(".h-100 a::attr(href)").extract()):
                # extract data from all the articles on current page
                self.pause.wait(5.0) # this causes the response mentioned above
                yield scrapy.Request(href, callback=self.parse_article)
                self.article_num += 1

            # move to next page
            next_page = 'https://www.information-age.com/page/'+str(page_num)+'/...'
            yield scrapy.Request(next_page, callback=self.parse)

    def parse_article(self, response):
        # function to extract desired data from website that is being scraped
python multithreading scrapy twisted
1个回答
1
投票

我不认为线程中的time.sleep和waits可以在Scrapy中很好地工作,因为它的工作方式是异步的。你可以做的是以下几点。

  • 你可以在settings.py中加入DOWNLOAD_DELAY=5,使请求之间的延迟在2.5到7.5秒之间。
  • 在 RANDOMIZE_DOWNLOAD_DELAY=False 的情况下,它将在中间精确地等待 5 秒。
  • 设置 CONCURRENT_REQUESTS=1 可以确保没有多个请求同时运行。
© www.soinside.com 2019 - 2024. All rights reserved.