【问题标题】:Adding pause in Scrapy spider在 Scrapy 蜘蛛中添加暂停
【发布时间】:2020-05-04 15:19:15
【问题描述】:

您好,我想创建一个每天抓取一个网站的蜘蛛。我有一个爬虫,它会刮掉我需要的所有东西,但我需要在每篇文章刮掉后实现暂停。我也尝试过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】:

    我不认为 time.sleep 和线程等待可以在 Scrapy 中很好地工作,因为它的异步工作方式。 您可以执行以下操作:

    • 您可以在 settings.py 中设置 DOWNLOAD_DELAY=5 以使请求之间的延迟在 2.5 到 7.5 秒之间
    • 使用 RANDOMIZE_DOWNLOAD_DELAY=False 时,它​​将恰好等待 5 秒。
    • 设置 CONCURRENT_REQUESTS=1 将确保没有多个请求同时运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      相关资源
      最近更新 更多