pytcharm运行单个爬虫:
# -*- coding: utf-8 -*-
# @Time : 2019/7/19 下午 5:19
# @Author : lh
# @Email : [email protected]
# @File : manage.py
# @Software: PyCharm
import sys
from scrapy.cmdline import execute
"""
单个爬虫自定义命令。可以不用在cmd跑了
"""
if __name__ == '__main__':
# scrapy crawl douban --nolog 与这个命令是等同的
execute(['scrapy', 'crawl', 'douban', '--nolog'])
上面是运行单个爬虫的命令:但是我总不能一个个的写然后再运行,这时还有一种自定制的方法可以使用(一次跑起来所以的爬虫):
1.在spider同级目录下创建任意名字的目录,我这边是custom_command
2.在custom_command下创建一个crawl_all(这个文件名就是自定义的命令),
# -*- coding: utf-8 -*-
# @Time : 2019/7/19 下午 5:33
# @Author : lh
# @Email : [email protected]
# @File : crawl_all.py
# @Software: PyCharm
from scrapy.commands import ScrapyCommand
from scrapy.utils.project import get_project_settings
class Command(ScrapyCommand):
requires_project = True
def syntax(self):
return '[options]'
def short_desc(self):
return 'Runs 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 = 'scrapy_tesy.custom_command'
然后你可以在cmd下运行scrapy crawl_all 命令了:
也可以使其在pycharm下跑起来。原理是和单个爬虫跑起来是一样的:
import sys
from scrapy.cmdline import execute
"""
单个爬虫自定义命令。可以不用在cmd跑了
"""
if __name__ == '__main__':
# execute(['scrapy', 'crawl', 'douban', '--nolog'])
# 自定义命令的运行
execute(['scrapy', 'crawl_all', '--nolog'])
有关解析:
如:
还有: