爬蟲入門很容易!就看你的學習方法了!來試試scrapy入門!

scrapy作為一款強大的爬蟲框架,當然要好好學習一番,本文便是本人學習和使用scrapy過後的一個總結,內容比較基礎,算是入門筆記吧,主要講述scrapy的基本概念和使用方法。

爬蟲入門很容易!就看你的學習方法了!來試試scrapy入門!

爬蟲入門很容易!就看你的學習方法了!來試試scrapy入門!

需要說明的是,項目管道( Item Pipeline )主要完成數據清洗,驗證,持久化存儲等工作;下載器中間件( Downloader Middlewares )作為下載器和引擎之間的的鉤子( hook ),用於監聽或修改下載請求或已下載的網頁,比如修改請求包的頭部信息等;爬蟲中間件( Spider Middlewares )作為爬蟲和引擎之間的鉤子( hook ),用於處理爬蟲的輸入輸出,即網頁 response 和爬蟲解析網頁後得到的 Items 和 requests 。

Items

至於什麼是 Items ,個人認為就是經爬蟲解析後得到的一個數據單元,包含一組數據,比如爬取的是某網站的商品信息,那麼每爬取一個網頁可能會得到多組商品信息,每組信息包含商品名稱,價格,生產日期,商品樣式等,那我們便可以定義一組 Item

爬蟲入門很容易!就看你的學習方法了!來試試scrapy入門!

Install

with pip

pip install scrapy

or conda

conda install -c conda-forge scrapy

基本指令如下:

D:\WorkSpace>scrapy --helpScrapy 1.5.0 - no active projectUsage: scrapy  [options] [args]Available commands: bench Run quick benchmark test fetch Fetch a URL using the Scrapy downloader genspider Generate new spider using pre-defined templates runspider Run a self-contained spider (without creating a project) settings Get settings values shell Interactive scraping console startproject Create new project version Print Scrapy version view Open URL in browser, as seen by Scrapy [ more ] More commands available when run from project directoryUse "scrapy  -h" to see more info about a command

如果需要使用虛擬環境,需要安裝 virtualenv

pip install virtualenv

scrapy startproject

scrapy startproject  [project-dir]

使用該指令可以生成一個新的 scrapy 項目,以 demo 為例

$ scrapy startproject demo...You can start your first spider with: cd demo scrapy genspider example example.com$ cd demo$ tree.├── demo│ ├── __init__.py│ ├── items.py│ ├── middlewares.py│ ├── pipelines.py│ ├── __pycache__│ ├── settings.py│ └── spiders│ ├── __init__.py│ └── __pycache__└── scrapy.cfg4 directories, 7 files

可以看到 startproject 自動生成了一些文件夾和文件,其中:

  1. scrapy.cfg : 項目配置文件,一般不用修改
  2. items.py : 定義 items 的文件,例如上述的 GoodsItem
  3. middlewares.py : 中間件代碼,默認包含下載器中間件和爬蟲中間件
  4. pipelines.py : 項目管道,用於處理 spider 返回的 items ,包括清洗,驗證,持久化等
  5. settings.py : 全局配置文件,包含各類全局變量
  6. spiders : 該文件夾用於存儲所有的爬蟲文件,注意一個項目可以包含多個爬蟲
  7. __init__.py : 該文件指示當前文件夾屬於一個 python 模塊
  8. __pycache__ : 存儲解釋器生成的 .pyc 文件(一種跨平臺的字節碼 byte code ),在 python2 中該類文件與 .py 保存在相同文件夾

scrapy genspider

項目生成以後,可以使用 scrapy genspider 指令自動生成一個爬蟲文件,比如,如果要爬取花瓣網首頁,執行以下指令:

$ cd demo$ scrapy genspider huaban www.huaban.com

默認生成的爬蟲文件 huaban.py 如下:

# -*- coding: utf-8 -*-import scrapyclass HuabanSpider(scrapy.Spider): name = 'huaban' allowed_domains = ['www.huaban.com'] start_urls = ['http://www.huaban.com/'] def parse(self, response): passscrapy.Spidernameallowed_domainsstart_urls

如果要自定義起始鏈接,也可以重寫 scrapy.Spider 類的 start_requests 函數,此處不予細講。

parse 函數是一個默認的回調函數,當下載器下載網頁後,會調用該函數進行解析,response 就是請求包的響應數據。至於網頁內容的解析方法, scrapy 內置了幾種選擇器( Selector ),包括 xpath 選擇器、 CSS 選擇器和正則匹配。下面是一些選擇器的使用示例,方便大家更加直觀的瞭解選擇器的用法。

# xpath selectorresponse.xpath('//a')response.xpath('./img').extract()response.xpath('//*[@id="huaban"]').extract_first()repsonse.xpath('//*[@id="Profile"]/div[1]/a[2]/text()').extract_first()# css selectorresponse.css('a').extract()response.css('#Profile > div.profile-basic').extract_first()response.css('a[href="test.html"]::text').extract_first()# re selectorresponse.xpath('.').re('id:\s*(\d+)')response.xpath('//a/text()').re_first('username: \s(.*)')

需要說明的是, response 不能直接調用 re , re_first .

scrapy crawl

假設爬蟲編寫完了,那就可以使用 scrapy crawl 指令開始執行爬取任務了。

當進入一個創建好的 scrapy 項目目錄時,使用 scrapy -h 可以獲得相比未創建之前更多的幫助信息,其中就包括用於啟動爬蟲任務的 scrapy crawl

$ scrapy -hScrapy 1.5.0 - project: huabanUsage: scrapy  [options] [args]Available commands: bench Run quick benchmark test check Check spider contracts crawl Run a spider edit Edit spider fetch Fetch a URL using the Scrapy downloader genspider Generate new spider using pre-defined templates list List available spiders parse Parse URL (using its spider) and print the results runspider Run a self-contained spider (without creating a project) settings Get settings values shell Interactive scraping console startproject Create new project version Print Scrapy version view Open URL in browser, as seen by ScrapyUse "scrapy  -h" to see more info about a command$ scrapy crawl -hUsage===== scrapy crawl [options] Run a spiderOptions=======--help, -h show this help message and exit-a NAME=VALUE set spider argument (may be repeated)--output=FILE, -o FILE dump scraped items into FILE (use - for stdout)--output-format=FORMAT, -t FORMAT format to use for dumping items with -oGlobal Options----------------logfile=FILE log file. if omitted stderr will be used--loglevel=LEVEL, -L LEVEL log level (default: DEBUG)--nolog disable logging completely--profile=FILE write python cProfile stats to FILE--pidfile=FILE write process ID to FILE--set=NAME=VALUE, -s NAME=VALUE set/override setting (may be repeated)--pdb enable pdb on failure

從 scrapy crawl 的幫助信息可以看出,該指令包含很多可選參數,但必選參數只有一個,就是 spider ,即要執行的爬蟲名稱,對應每個爬蟲的名稱( name )。

scrapy crawl huaban

至此,一個 scrapy 爬蟲任務的創建和執行過程就介紹完了,至於實例,後續博客會陸續介紹。

scrapy shell

最後簡要說明一下指令 scrapy shell ,這是一個交互式的 shell ,類似於命令行形式的python ,當我們剛開始學習 scrapy 或者剛開始爬蟲某個陌生的站點時,可以使用它熟悉各種函數操作或者選擇器的使用,用它來不斷試錯糾錯,熟練掌握 scrapy 各種用法。

$ scrapy shell www.huaban.com2018-05-29 23:58:49 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: scrapybot)2018-05-29 23:58:49 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9.5, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.6.3 (v3.6.3:2c5fed8, Oct 32017, 17:26:49) [MSC v.1900 32 bit (Intel)], pyOpenSSL 17.5.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.2.2, Platform Windows-10-10.0.17134-SP02018-05-29 23:58:49 [scrapy.crawler] INFO: Overridden settings: {'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter', 'LOGSTATS_INTERVAL': 0}2018-05-29 23:58:49 [scrapy.middleware] INFO: Enabled extensions:['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole']2018-05-29 23:58:50 [scrapy.middleware] INFO: Enabled downloader middlewares:['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats']2018-05-29 23:58:50 [scrapy.middleware] INFO: Enabled spider middlewares:['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware']2018-05-29 23:58:50 [scrapy.middleware] INFO: Enabled item pipelines:[]2018-05-29 23:58:50 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:60232018-05-29 23:58:50 [scrapy.core.engine] INFO: Spider opened2018-05-29 23:58:50 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to  from 2018-05-29 23:58:50 [scrapy.core.engine] DEBUG: Crawled (200)  (referer: None)[s] Available Scrapy objects:[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)[s] crawler [s] item {}[s] request [s] response <200 http://huaban.com/>[s] settings [s] spider [s] Useful shortcuts:[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)[s] fetch(req) Fetch a scrapy.Request and update local objects[s] shelp() Shell help (print this help)[s] view(response) View response in a browserIn [1]: view(response)Out[1]: TrueIn [2]: response.xpath('//a')Out[2]:[, , , , , ]In [3]: response.xpath('//a').extract()Out[3]:[' ', ' ', ' ', ' ', ' ', ' ']In [4]: response.xpath('//img')Out[4]: []In [5]: response.xpath('//a/text()')Out[5]:[, , , , ]In [6]: response.xpath('//a/text()').extract()Out[6]: ['添加採集', '添加畫板', '安裝採集工具', ' ', ' ']In [7]: response.xpath('//a/text()').extract_first()Out[7]: '添加採集' 
爬蟲入門很容易!就看你的學習方法了!來試試scrapy入門!


分享到:


相關文章: