scrapy之自定制命令

写好自己的爬虫项目之后,可以自己定制爬虫运行的命令。

一、单爬虫

在项目的根目录下新建一个py文件,如命名为start.py,写入如下代码:

from scrapy.cmdline import execute

if __name__ == "__main__":
    execute(["scrapy", "crawl", "chouti", "--nolog"])

运行start.py即可。

二、多爬虫运行

1、在spiders的同级目录创建文件夹,如commands;

2、在这个新建的文件夹下创建一个py文件,如命名为crawlall.py,编写代码:

from scrapy.commands import ScrapyCommand


class Command(ScrapyCommand):
    requires_project = True

    def syntax(self):
        return "[options]"

    def short_desc(self):
        return "Run all of the spiders"  # 自定义命令描述

    def run(self, args, opts):
        spider_list = self.crawler_process.spiders.list()  # 获取爬虫列表
        for name in spider_list:  # 循环列表,对每个爬虫进行爬取。也可以对列表中的爬虫进行筛选,根据自己的需求爬取想要的
            self.crawler_process.crawl(name, **opts.__dict__)
        self.crawler_process.start()

3、在settings.py中添加配置:COMMANDS_MODULE = "项目名.目录名"

如:COMMANDS_MODULE = "my_scrapy.commands"

4、在终端输入:scrapy crawlall --nolog 即可运行  (crawlall是步骤2中你新建的py文件名)

原文地址:https://www.cnblogs.com/yanlin-10/p/9842729.html