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

來源:互聯網
上載者:User

標籤:服務   color   des   short   背景   分享圖片   run   set   highlight   

背景:

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

小白解決辦法:

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

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

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

from scrapy.cmdline import executeexecute([‘scrapy‘,‘crawl‘,‘httpbin‘])

  

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

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

  2、在其中建立 crawlall.py 檔案 (此處檔案名稱就是自訂的命令)

  

  

crawlall.py
from scrapy.commands import ScrapyCommandfrom scrapy.utils.project import get_project_settingsclass 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爬行任務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.