1. 程式人生 > >python爬蟲scrapy之如何同時執行多個scrapy爬行任務

python爬蟲scrapy之如何同時執行多個scrapy爬行任務

還需 學習 lis 參數 文件名 其中 .project 自定義 com

背景:

  剛開始學習scrapy爬蟲框架的時候,就在想如果我在服務器上執行一個爬蟲任務的話,還說的過去。但是我不能每個爬蟲任務就新建一個項目吧。例如我建立了一個知乎的爬行任務,但是我在這個爬行任務中,寫了多個spider,重要的是我想讓他們同時運行,怎麽辦?

小白解決辦法:

  1、在spiders同目錄下新建一個run.py文件,內容如下(列表裏面最後可以加上參數,如--nolog)

  2、小白想了(當時的我),這樣也行,mygod,那我豈不是多寫幾行就行就行了麽,結果(結果白癡了),小白又想,那加個while循環,把爬蟲名字都寫入一個列表,這樣循環拿到每個spiders的name,結果更慘。

  3、下面命令只限於,快速調試的作用或一個項目下單個spider的爬行任務。

from scrapy.cmdline import execute

execute([‘scrapy‘,‘crawl‘,‘httpbin‘])

  

通過學習才知道原來是這樣子:

  1、在spiders同級創建任意目錄,如:commands

  2、在其中創建 crawlall.py 文件 (此處文件名就是自定義的命令)

  技術分享圖片

  

crawlall.py
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 = zhihuuser.commands

  4、那麽問題來了,如果我在spiders寫了多個爬行任務,我上面說了這麽多,我最終需要怎麽執行,so easy!你可以直接把下面這個命令放到計劃任務裏面,就行了。

scrapy crawlall

python爬蟲scrapy之如何同時執行多個scrapy爬行任務