写好本身的爬虫项目以后,能够本身定制爬虫运行的命令。html
1、单爬虫python
在项目的根目录下新建一个py文件,如命名为start.py,写入以下代码:框架
from scrapy.cmdline import execute if __name__ == "__main__": execute(["scrapy", "crawl", "chouti", "--nolog"])
运行start.py便可。scrapy
2、多爬虫运行ide
一、在spiders的同级目录建立文件夹,如commands;post
二、在这个新建的文件夹下建立一个py文件,如命名为crawlall.py,编写代码:ui
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()
三、在settings.py中添加配置:COMMANDS_MODULE = "项目名.目录名"url
如:COMMANDS_MODULE = "myspider.spiders.commands"spa
四、在终端输入:scrapy crawlall --nolog 便可运行 (crawlall是步骤2中你新建的py文件名)code
目录结构
└─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