2013年4月15日 星期一

scrapy 快速上手



Scrapy中各個模組切得很乾淨,該分的都已經分好,只要了解各模組的運作流程就能快速上手。


  • Overview

     Project -> spiders -> myspider.py =>爬網站邏輯, 取欄位or發Request爬下一層
                -> items.py => 定義在Scrapy中傳遞的物件field
                -> pipeline.py => 儲存DB的邏輯
                -> middlewares.py  => 各個Scrapy模組間的橋梁(請參考附圖) 分 Downloader, Spider, Scheduler
                -> settings.py => 各種設定參數 https://scrapy.readthedocs.org/en/latest/topics/settings.html



  • 常用Console指令

startproject : 開project
shell : 試爬一個網址(寫Spider主程式邏輯時很需要)
crawl : 執行一個完整的spider
list : 列出目前project的spider
deploy : 佈署相關


  • Spider

    Scrapy中的Spider有很多種:BaseSpider, CrawSpider, CSVFeedSpider,...,依照網站複雜度跟特性使用對應的Spider

    爬黃頁只需要用BaseSpider
    class MySpider(BaseSpider):
    name                          : Spider名稱
    allowed_domains[]             : 如其名
    start_urls[]                  : 裡頭可以裝一串要爬的網址
    start_requests()              : 可以取代start_urls用iterable物件產生url (高級物,沒特別不需覆寫)
    make_requests_from_url(url)        : 會取start_urls裡的url送成Request物件 (高級物,沒特別不需覆寫)
    parse(response)                             : BaseSpider預設的callback function,回傳Response物件
  https://scrapy.readthedocs.org/en/latest/topics/request-response.html

  主要邏輯寫在Request定義的callback function裡面(預設是parse)
  return an iterable of Request (繼續爬下一頁) and/or Item (丟給pipeline儲存) objects.


  • hxs

    高級物,請自學,
    可用  scrapy shell http://網址.com  來測試
     

  • Log

  from scrapy import log
  log.msg("Hellow World!", level=log.ERROR)

  level:
CRITICAL - for critical errors
ERROR - for regular errors
WARNING - for warning messages
INFO - for informational messages
DEBUG - for debugging messages
    在setting.py設定觀看等級



  • Middleware

  Middleware有千奇百萬種,主要用途在各模組間加料。ex:Proxy,Cookie,Login https://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html?highlight=Middleware

  ex:
  DownloadMiddleware
    process_request(request, spider)                       : request時
    process_response(request, response, spider)      : response時
    process_exception(request, exception, spider)    : 發生exception時



  • Deploy

  主要好處由scrapyd幫你管理spider,可以發簡單的curl就能控制監控執行中的spider。

  環境設置
  https://scrapy.readthedocs.org/en/latest/topics/scrapyd.html?highlight=deploy
 
  常用指令
    scrapy deploy scrapyd -p yourproject
    curl http://localhost:6800/schedule.json -d project=yourproject -d spider=spidername
    curl http://localhost:6800/listjobs.json?project=yourproject
    curl http://localhost:6800/cancel.json -d project=yourproject -d job=jobid

沒有留言:

張貼留言