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/qiu-hua/p/12638793.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步