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文件名)

  • 相关阅读:
    SqlServer存储过程函数加解密[极有用]
    BMDThread控件动态创建多线程示例
    cxGrid右键自定义菜单
    越狱中Michael的一种疾病
    静态链表
    单行编辑框SelectText()
    开机得按F1
    jquery调用页面后台方法‏
    .net调用存储过程详解
    javascript兼容各种浏览器的异步请求
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/12638793.html
Copyright © 2011-2022 走看看