python - 如何停止 scrapy 蜘蛛但处理所有想要的项目?

标签 python mysql scrapy

我的管道中有一个方法来检查项目的发布日期是否早于在 mysql 中找到的发布日期,所以让 lastseen 成为从数据库中检索到的最新日期时间:

def process_item(self, item, spider):
    if item['post_date'] < lastseen:
        # set flag to close_spider
        # raise DropItem("old item")

这段代码基本上可以工作,除了:我每小时检查一次网站只是为了获得新帖子,如果我不阻止蜘蛛它会继续在数千页上爬行,如果我在标志上停止蜘蛛,机会是很少有请求不会被处理,因为它们可能会在蜘蛛关闭后返回队列,即使这些请求在发布日期可能较新,话虽如此,是否有更精确的抓取的解决方法?

谢谢,

最佳答案

不确定这是否适合您的设置,但您可以获取 lastseen当初始化你的蜘蛛时从 MySQL 并停止在你的回调中生成请求当响应包含带有 postdate < lastseen 的项目时,因此基本上移动了逻辑以停止直接在蜘蛛而不是管道内爬行。

有时向你的蜘蛛传递一个参数会更简单

scrapy crawl myspider -a lastseen=20130715

并设置蜘蛛的属性以在回调中进行测试(http://doc.scrapy.org/en/latest/topics/spiders.html#spider-arguments)

class MySpider(BaseSpider):
    name = 'myspider'

    def __init__(self, lastseen=None):
        self.lastseen = lastseen
        # ...


    def parse_new_items(self, reponse):

        follow_next_page = True

        # item fetch logic
        for element in <some_selector>:

            # get post_date
            post_date = <extract post_date from element>

            # check post_date
            if post_date < self.lastseen:
                follow_next_page = False
                continue

            item = MyItem()
            # populate item...
            yield item

        # find next page to crawl
        if follow_next_page:

            next_page_url = ...

            yield Request(url = next_page_url, callback=parse_new_items)

关于python - 如何停止 scrapy 蜘蛛但处理所有想要的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17666295/

相关文章:

python - csympy cmake 错误 : Compiler does not support C++11 constructs

python - 如何在 python 中循环具有子菜单的菜单?

python - Pygame 可以在 64 位 Python 2.7 上运行吗?

MySQL查询重写没有子查询可能吗?

python - Django-Nginx 补丁请求 :405 Method \"METHOD_OTHER\" not allowed

mysql - 使用批处理文件自动备份 MySQL

PHP/HTML 表单进入数据库复选框验证

python - 使用多处理运行多个 Scrapy 的最佳方式是什么?

python - ImportError:无法导入名称解包

python - django 动态蜘蛛错误 "check_mandatory_vars"