【问题标题】:Force my scrapy spider to stop crawling强迫我的爬虫停止爬行
【发布时间】:2023-03-05 14:00:01
【问题描述】:

如果条件为真(如 scrap_item_id == predefine_value ),是否有机会停止抓取。我的问题类似于Scrapy - how to identify already scraped urls,但我想在发现最后一个被刮掉的物品后“强制”我的刮擦蜘蛛停止爬行。

【问题讨论】:

  • 好的……我很确定有更好的解决方案,但是从 scrapy.project import crawler crawler.engine.close_spider(spider, 'closespider_blee') 有效
  • 该解决方案似乎很好。它也用于 scrapy 源代码(例如 contrib/closespider.py)

标签: python scrapy


【解决方案1】:

在 GitHub 上提供的最新版 Scrapy 中,您可以引发 CloseSpider 异常来手动关闭蜘蛛。

在0.14 release note doc中提到:“添加CloseSpider异常手动关闭蜘蛛(r2691)”

文档中的示例:

def parse_page(self, response):
  if 'Bandwidth exceeded' in response.body:
    raise CloseSpider('bandwidth_exceeded')

另见:http://readthedocs.org/docs/scrapy/en/latest/topics/exceptions.html?highlight=closeSpider

【讨论】:

  • 强制停止成功,但速度不够快。它仍然让一些请求运行。希望 Scrapy 以后能提供更好的解决方案。
  • 根据我的观察,它完成了已经触发的请求,不是吗?
【解决方案2】:

这个问题是 8 个月前提出的,但我想知道同样的事情并找到了另一个(不是很好)解决方案。希望这可以帮助未来的读者。

我正在连接到管道文件中的数据库,如果数据库连接不成功,我希望 Spider 停止爬行(如果无处可发送,则收集数据毫无意义)。我最终做的是使用:

from scrapy.project import crawler
crawler._signal_shutdown(9,0) #Run this if the cnxn fails.

这会导致蜘蛛执行以下操作:

[scrapy] INFO: Received SIGKILL, shutting down gracefully. Send again to force unclean shutdown.

在阅读了您的评论并浏览了“/usr/local/lib/python2.7/dist-packages/Scrapy-0.12.0.2543-py2.7.egg/scrapy/crawler. py”文件。我不完全确定它在做什么,传递给函数的第一个数字是签名(例如,使用 3,0 而不是 9,0 返回错误[scrapy] INFO: Received SIGKILL...

但似乎工作得很好。快乐刮。

编辑: 我还认为您可以通过以下方式强制您的程序关闭:

import sys
sys.exit("SHUT DOWN EVERYTHING!")

【讨论】:

【解决方案3】:

从管道来看,我更喜欢以下解决方案。

class MongoDBPipeline(object):

def process_item(self, item, spider):
    spider.crawler.engine.close_spider(self, reason='duplicate')

来源:Force spider to stop in scrapy

【讨论】:

    【解决方案4】:

    尝试了很多选项,但没有任何效果。这个肮脏的黑客对 Linux 有用:

    os.kill(os.getpid(), signal.SIGINT)
    os.kill(os.getpid(), signal.SIGINT)
    

    这会向scrapy发送两次SIGINT信号。第二个信号强制关机

    【讨论】:

    • 我在 Linux 上试过这个,但我得到:“NameError: name 'signal' is not defined”
    • 添加import signal
    猜你喜欢
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2016-01-25
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多