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 = "myspider.spiders.commands"

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

    目录结构

     └─myspider
            │  items.py
            │  middlewares.py
            │  pipelines.py
            │  settings.py
            │  __init__.py
            │
            ├─spiders
            │  │  zhihu.py
            │  │  __init__.py
            │  │
            │  ├─commands
            │  │  │  crawlall.py
            │  │  │
            │  │  └─__pycache__
            │  │          crawlall.cpython-36.pyc
            │  │
            │  └─__pycache__
            │          zhihu.cpython-36.pyc
            │          __init__.cpython-36.pyc
            │
            └─__pycache__
                    items.cpython-36.pyc
                    pipelines.cpython-36.pyc
                    settings.cpython-36.pyc
                    __init__.cpython-36.pyc
  • 相关阅读:
    arrayPointer
    shellAPP
    docker
    程序运行时内存管理
    C++ deepin
    coreOS+Docker新一代企业轻量级Linux
    玩转docker
    古典小说丛书系列软件
    读《追随智慧》(一)
    高速基于echarts的大数据可视化
  • 原文地址:https://www.cnblogs.com/songzhixue/p/11491182.html
Copyright © 2011-2022 走看看