zoukankan      html  css  js  c++  java
  • 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文件名)

  • 相关阅读:
    数据库系列之查询(4)
    数据库系列之查询(3)
    数据库系列之查询(2)
    数据库系列之查询(1)
    数据库系列之视图
    数据库系列之数据管理(删除数据)
    数据库系列之数据管理(更新数据)
    数据库系列之数据管理(插入数据)
    数据库管理之数据表管理(2)
    数据库管理之数据表管理(1)
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/12638793.html
Copyright © 2011-2022 走看看