美文网首页
scrapy启动多爬虫

scrapy启动多爬虫

作者: _张旭 | 来源:发表于2018-07-14 17:16 被阅读0次

一般启动方式

scrapy crawl spider_name

命令行启动好处是灵活方便, 可以通过传递参数的形式控制爬虫的行为和输出。

参见官方文档

比如你可以配置爬虫采集到数据的输出方式:

scrapy crawl dmoz -o items.json

但是它的缺点也很明显:

  • 原子性太强,不方便动态调试代码
  • 当需要启动多个爬虫时,不方便操作

新的思路

我们知道Scrapy是基于Twisted实现的爬虫框架, 因此我们可以通过引入reactor来启动我们的爬虫。

为了方便理解,我把的项目结构展示出来:

.
├── learn_scrapy
│   ├── __init__.py
│   ├── items.py
│   ├── middlewares.py
│   ├── pipelines.py
│   ├── settings.py
│   └── spiders
│       ├── __init__.py
│       └── test.py
├── debug.py
└── scrapy.cfg

我在项目根目录下新建了文件 debug.py

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.project import get_project_settings
from scrapy.utils.log import configure_logging
# 引入spider
from learn_scrapy.spiders.test import TestSpider
import logging


logger = logging.getLogger(__name__)

settings = get_project_settings()
configure_logging(settings)
runner = CrawlerRunner(settings)


def start_spider():
    # 装载爬虫
    runner.crawl(TestSpider)
    # 如果有多个爬虫需要启动可以一直装载下去
    # runner.crawl(TestSpider2)
    # runner.crawl(TestSpider3)
    # runner.crawl(TestSpider4)
    # ... ...
    
    # 爬虫结束后停止事件循环
    d = runner.join()
    d.addBoth(lambda _: reactor.stop())

    # 启动事件循环
    reactor.run()


def main():
    start_spider()


if __name__ == '__main__':
    main()

运行这个文件python3 debug.py就可以启动爬虫。

动态调试

在IDE下选择启动debug:

image

可以看到程序停在了断点处,可以很方便的查看程序运行时的堆栈和变量信息:

image

相关文章

网友评论

      本文标题:scrapy启动多爬虫

      本文链接:https://www.haomeiwen.com/subject/vopypftx.html