Scrapy入門教程

關鍵字:scrapy入門教程爬蟲Spider
作者:http://www.cnblogs.com/txw1958/
出處:http://www.cnblogs.com/txw1958/archive/2012/07/16/scrapy-tutorial.html


在這篇入門教程中,我們假定你已經安裝了Scrapy。如果你還沒有安裝,那麼請參考安裝指南

我們將使用開放目錄項目(dmoz)作爲抓取的例子。

這篇入門教程將引導你完成如下任務:

  1. 創建一個新的Scrapy項目

  2. 定義提取的Item

  3. 寫一個Spider用來爬行站點,並提取Items

  4. 寫一個Item Pipeline用來存儲提取出的Items

Scrapy是由Python編寫的。如果你是Python新手,你也許希望從瞭解Python開始,以期最好的使用Scrapy。如果你對其它編程語言熟悉,想快速的學習Python,這裏推薦 Dive Into Python。如果你對編程是新手,且想從Python開始學習編程,請看下面的對非程序員的Python資源列表


新建工程

在抓取之前,你需要新建一個Scrapy工程。進入一個你想用來保存代碼的目錄,然後執行:

Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.T:\>scrapy startproject tutorialT:\>

這個命令會在當前目錄下創建一個新目錄tutorial,它的結構如下:

複製代碼
T:\tutorial>tree /fFolder PATH listingVolume serial number is 0006EFCF C86A:7C52T:.│  scrapy.cfg│└─tutorial    │  items.py    │  pipelines.py    │  settings.py    │  __init__.py    │    └─spiders            __init__.py
複製代碼

這些文件主要是:

  • scrapy.cfg: 項目配置文件

  • tutorial/: 項目python模塊, 呆會代碼將從這裏導入

  • tutorial/items.py: 項目items文件

  • tutorial/pipelines.py: 項目管道文件

  • tutorial/settings.py: 項目配置文件

  • tutorial/spiders: 放置spider的目錄


定義Item

Items是將要裝載抓取的數據的容器,它工作方式像python裏面的字典,但它提供更多的保護,比如對未定義的字段填充以防止拼寫錯誤。

它通過創建一個scrapy.item.Item類來聲明,定義它的屬性爲scrpy.item.Field對象,就像是一個對象關係映射(ORM).
我們通過將需要的item模型化,來控制從dmoz.org獲得的站點數據,比如我們要獲得站點的名字,url和網站描述,我們定義這三種屬性的域。要做到這點,我們編輯在tutorial目錄下的items.py文件,我們的Item類將會是這樣

from scrapy.item import Item, Field class DmozItem(Item):    title = Field()    link = Field()    desc = Field()

剛開始看起來可能會有些困惑,但是定義這些item能讓你用其他Scrapy組件的時候知道你的 items到底是什麼。



我們的第一個爬蟲(Spider)

Spider是用戶編寫的類,用於從一個域(或域組)中抓取信息。

他們定義了用於下載的URL的初步列表,如何跟蹤鏈接,以及如何來解析這些網頁的內容用於提取items。

要建立一個Spider,你必須爲scrapy.spider.BaseSpider創建一個子類,並確定三個主要的、強制的屬性:

  • name:爬蟲的識別名,它必須是唯一的,在不同的爬蟲中你必須定義不同的名字.

  • start_urls:爬蟲開始爬的一個URL列表。爬蟲從這裏開始抓取數據,所以,第一次下載的數據將會從這些URLS開始。其他子URL將會從這些起始URL中繼承性生成。

  • parse():爬蟲的方法,調用時候傳入從每一個URL傳回的Response對象作爲參數,response將會是parse方法的唯一的一個參數,

這個方法負責解析返回的數據、匹配抓取的數據(解析爲item)並跟蹤更多的URL。


這是我們的第一隻爬蟲的代碼,將其命名爲dmoz_spider.py並保存在tutorial\spiders目錄下。

按 Ctrl+C 複製代碼
按 Ctrl+C 複製代碼



爬爬爬

爲了讓我們的爬蟲工作,我們返回項目主目錄執行以下命令

T:\tutorial>scrapy crawl dmoz

crawl dmoz 命令從dmoz.org域啓動爬蟲。 你將會獲得如下類似輸出

複製代碼
T:\tutorial>scrapy crawl dmoz2012-07-13 19:14:45+0800 [scrapy] INFO: Scrapy 0.14.4 started (bot: tutorial)
2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled item pipelines:2012-07-13 19:14:45+0800 [dmoz] INFO: Spider opened2012-07-13 19:14:45+0800 [dmoz] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2012-07-13 19:14:45+0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2012-07-13 19:14:45+0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2012-07-13 19:14:46+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/> (referer: None)
2012-07-13 19:14:46+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> (referer: None)
2012-07-13 19:14:46+0800 [dmoz] INFO: Closing spider (finished)
2012-07-13 19:14:46+0800 [dmoz] INFO: Dumping spider stats:        {'downloader/request_bytes': 486,         'downloader/request_count': 2,         'downloader/request_method_count/GET': 2,         'downloader/response_bytes': 13063,         'downloader/response_count': 2,         'downloader/response_status_count/200': 2,         'finish_reason': 'finished',         'finish_time': datetime.datetime(2012, 7, 13, 11, 14, 46, 703000),         'scheduler/memory_enqueued': 2,         'start_time': datetime.datetime(2012, 7, 13, 11, 14, 45, 500000)}2012-07-13 19:14:46+0800 [dmoz] INFO: Spider closed (finished)
2012-07-13 19:14:46+0800 [scrapy] INFO: Dumping global stats:        {}
複製代碼

注意包含 [dmoz]的行 ,那對應着我們的爬蟲。你可以看到start_urls中定義的每個URL都有日誌行。因爲這些URL是起始頁面,所以他們沒有引用(referrers),所以在每行的末尾你會看到 (referer: <None>).
有趣的是,在我們的 parse  方法的作用下,兩個文件被創建:分別是 Books 和 Resources,這兩個文件中有URL的頁面內容。

發生了什麼事情?

Scrapy爲爬蟲的 start_urls屬性中的每個URL創建了一個 scrapy.http.Request 對象 ,並將爬蟲的parse 方法指定爲回調函數。
這些 Request首先被調度,然後被執行,之後通過parse()方法,scrapy.http.Response 對象被返回,結果也被反饋給爬蟲。



提取Item

選擇器介紹

我們有很多方法從網站中提取數據。Scrapy 使用一種叫做 XPath selectors的機制,它基於 XPath表達式。如果你想了解更多selectors和其他機制你可以查閱資料http://doc.scrapy.org/topics/selectors.html#topics-selectors
這是一些XPath表達式的例子和他們的含義

  • /html/head/title: 選擇HTML文檔<head>元素下面的<title> 標籤。

  • /html/head/title/text(): 選擇前面提到的<title> 元素下面的文本內容

  • //td: 選擇所有 <td> 元素

  • //div[@class="mine"]: 選擇所有包含 class="mine" 屬性的div 標籤元素

這只是幾個使用XPath的簡單例子,但是實際上XPath非常強大。如果你想了解更多XPATH的內容,我們向你推薦這個XPath教程http://www.w3schools.com/XPath/default.asp

爲了方便使用XPaths,Scrapy提供XPathSelector 類, 有兩種口味可以選擇, HtmlXPathSelector (HTML數據解析) 和XmlXPathSelector (XML數據解析)。 爲了使用他們你必須通過一個 Response 對象對他們進行實例化操作。你會發現Selector對象展示了文檔的節點結構。因此,第一個實例化的selector必與根節點或者是整個目錄有關 。
Selectors 有三種方法

  • select():返回selectors列表, 每一個select表示一個xpath參數表達式選擇的節點.

  • extract():返回一個unicode字符串,該字符串爲XPath選擇器返回的數據

  • re(): 返回unicode字符串列表,字符串作爲參數由正則表達式提取出來

嘗試在shell中使用Selectors

爲了演示Selectors的用法,我們將用到 內建的Scrapy shell,這需要系統已經安裝IPython (一個擴展python交互環境) 。

附IPython下載地址:http://pypi.python.org/pypi/ipython#downloads

要開始shell,首先進入項目頂層目錄,然後輸入

T:\tutorial>scrapy shell http://www.dmoz.org/Computers/Programming/Languages/Python/Books/

輸出結果類似這樣:

複製代碼
2012-07-16 10:58:13+0800 [scrapy] INFO: Scrapy 0.14.4 started (bot: tutorial)
2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled extensions: TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled item pipelines:2012-07-16 10:58:13+0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2012-07-16 10:58:13+0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2012-07-16 10:58:13+0800 [dmoz] INFO: Spider opened2012-07-16 10:58:18+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> (referer: None)[s] Available Scrapy objects:[s]   hxs        <HtmlXPathSelector xpath=None data=u'<html><head><meta http-equiv="Content-Ty'>[s]   item       {}[s]   request    <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>[s]   response   <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>[s]   settings   <CrawlerSettings module=<module 'tutorial.settings' from 'T:\tutorial\tutorial\settings.pyc'>>[s]   spider     <DmozSpider 'dmoz' at 0x1f68230>[s] Useful shortcuts:[s]   shelp()           Shell help (print this help)[s]   fetch(req_or_url) Fetch request (or URL) and update local objects[s]   view(response)    View response in a browserWARNING: Readline services not available or not loaded.WARNING: Proper color support under MS Windows requires the pyreadline library.You can find it at:http://ipython.org/pyreadline.htmlGary's readline needs the ctypes module, from:http://starship.python.net/crew/theller/ctypes(Note that ctypes is already part of Python versions 2.5 and newer).Defaulting color scheme to 'NoColor'Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]Type "copyright", "credits" or "license" for more information.IPython 0.13 -- An enhanced Interactive Python.?         -> Introduction and overview of IPython's features.%quickref -> Quick reference.help      -> Python's own help system.object?   -> Details about 'object', use 'object??' for extra details.In [1]:
複製代碼

Shell載入後,你將獲得迴應,這些內容被存儲在本地變量 response 中,所以如果你輸入response.body 你將會看到response的body部分,或者輸入response.headers 來查看它的 header部分。
Shell也實例化了兩種selectors,一個是解析HTML的  hxs 變量,一個是解析 XML 的 xxs 變量。我們來看看裏面有什麼:

複製代碼
In [1]: hxs.select('//title')Out[1]: [<HtmlXPathSelector xpath='//title' data=u'<title>Open Directory - Computers: Progr'>]In [2]: hxs.select('//title').extract()Out[2]: [u'<title>Open Directory - Computers: Programming: Languages: Python: Books</title>']In [3]: hxs.select('//title/text()')Out[3]: [<HtmlXPathSelector xpath='//title/text()' data=u'Open Directory - Computers: Programming:'>]In [4]: hxs.select('//title/text()').extract()Out[4]: [u'Open Directory - Computers: Programming: Languages: Python: Books']In [5]: hxs.select('//title/text()').re('(\w+):')Out[5]: [u'Computers', u'Programming', u'Languages', u'Python']In [6]:
複製代碼



提取數據

現在我們嘗試從網頁中提取數據。
你可以在控制檯輸入 response.body, 檢查源代碼中的 XPaths 是否與預期相同。然而,檢查HTML源代碼是件很枯燥的事情。爲了使事情變得簡單,我們使用Firefox的擴展插件Firebug。更多信息請查看Using Firebug for scrapingUsing Firefox for scraping.
txw1958注:事實上我用的是Google Chrome的Inspect Element功能,而且可以提取元素的XPath。
檢查源代碼後,你會發現我們需要的數據在一個 <ul>元素中,而且是第二個<ul>。
我們可以通過如下命令選擇每個在網站中的 <li> 元素:

hxs.select('//ul/li') 

然後是網站描述:

hxs.select('//ul/li/text()').extract()

網站標題:

hxs.select('//ul/li/a/text()').extract()

網站鏈接:

hxs.select('//ul/li/a/@href').extract()

如前所述,每個select()調用返回一個selectors列表,所以我們可以結合select()去挖掘更深的節點。我們將會用到這些特性,所以:

複製代碼
sites = hxs.select('//ul/li')for site in sites:    title = site.select('a/text()').extract()    link = site.select('a/@href').extract()    desc = site.select('text()').extract()    print title, link, desc
複製代碼


Note
更多關於嵌套選擇器的內容,請閱讀Nesting selectorsWorking with relative XPaths

將代碼添加到爬蟲中:

txw1958注:代碼有修改,綠色註釋掉的代碼爲原教程的,你懂的

複製代碼
from scrapy.spider import BaseSpiderfrom scrapy.selector import HtmlXPathSelectorclass DmozSpider(BaseSpider):    name = "dmoz"    allowed_domains = ["dmoz.org"]    start_urls = [        "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"]          def parse(self, response):        hxs = HtmlXPathSelector(response)        sites = hxs.select('//fieldset/ul/li')        #sites = hxs.select('//ul/li')for site in sites:            title = site.select('a/text()').extract()            link = site.select('a/@href').extract()            desc = site.select('text()').extract()            #print title, link, descprint title, link
複製代碼

現在我們再次抓取dmoz.org,你將看到站點在輸出中被打印 ,運行命令

T:\tutorial>scrapy crawl dmoz



使用條目(Item)

Item 對象是自定義的python字典,使用標準字典類似的語法,你可以獲取某個字段(即之前定義的類的屬性)的值:

>>> item = DmozItem() >>> item['title'] = 'Example title' 
>>> item['title'] 'Example title'

Spiders希望將其抓取的數據存放到Item對象中。爲了返回我們抓取數據,spider的最終代碼應當是這樣:

複製代碼
from scrapy.spider import BaseSpiderfrom scrapy.selector import HtmlXPathSelectorfrom tutorial.items import DmozItemclass DmozSpider(BaseSpider):   name = "dmoz"   allowed_domains = ["dmoz.org"]   start_urls = [       "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",       "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"   ]   def parse(self, response):       hxs = HtmlXPathSelector(response)       sites = hxs.select('//fieldset/ul/li')       #sites = hxs.select('//ul/li')   items = []       for site in sites:           item = DmozItem()           item['title'] = site.select('a/text()').extract()           item['link'] = site.select('a/@href').extract()           item['desc'] = site.select('text()').extract()           items.append(item)       return items
複製代碼

現在我們再次抓取 :

複製代碼
2012-07-16 14:52:36+0800 [dmoz] DEBUG: Scraped from <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>        {'desc': [u'\n\t\t\t\n\t',                  u' \n\t\t\t\n\t\t\t\t\t\n - Free Python books and tutorials.\n \n'],         'link': [u'http://www.techbooksforfree.com/perlpython.shtml'],         'title': [u'Free Python books']}2012-07-16 14:52:36+0800 [dmoz] DEBUG: Scraped from <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>        {'desc': [u'\n\t\t\t\n\t',                  u' \n\t\t\t\n\t\t\t\t\t\n - Annotated list of free online books on Python scripting language. Topics range from beginner to advanced.\n \n          '],         'link': [u'http://www.freetechbooks.com/python-f6.html'],         'title': [u'FreeTechBooks: Python Scripting Language']}2012-07-16 14:52:36+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/> (referer: None)
2012-07-16 14:52:36+0800 [dmoz] DEBUG: Scraped from <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/>        {'desc': [u'\n\t\t\t\n\t',                  u' \n\t\t\t\n\t\t\t\t\t\n - A directory of free Python and Zope hosting providers, with reviews and ratings.\n \n'],         'link': [u'http://www.oinko.net/freepython/'],         'title': [u'Free Python and Zope Hosting Directory']}2012-07-16 14:52:36+0800 [dmoz] DEBUG: Scraped from <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/>        {'desc': [u'\n\t\t\t\n\t',                  u' \n\t\t\t\n\t\t\t\t\t\n - Features Python books, resources, news and articles.\n \n'],         'link': [u'http://oreilly.com/python/'],         'title': [u"O'Reilly Python Center"]}2012-07-16 14:52:36+0800 [dmoz] DEBUG: Scraped from <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/>        {'desc': [u'\n\t\t\t\n\t',                  u' \n\t\t\t\n\t\t\t\t\t\n - Resources for reporting bugs, accessing the Python source tree with CVS and taking part in the development of Python.\n\n'],         'link': [u'http://www.python.org/dev/'],         'title': [u"Python Developer's Guide"]}
複製代碼


保存抓取的數據

保存信息的最簡單的方法是通過Feed exports,命令如下:

T:\tutorial>scrapy crawl dmoz -o items.json -t json

所有抓取的items將以JSON格式被保存在新生成的items.json 文件中

在像本教程一樣的小型項目中,這些已經足夠。然而,如果你想用抓取的items做更復雜的事情,你可以寫一個 Item Pipeline(條目管道)。因爲在項目創建的時候,一個專門用於條目管道的佔位符文件已經隨着items一起被建立,目錄在tutorial/pipelines.py。如果你只需要存取這些抓取後的items的話,就不需要去實現任何的條目管道。



結束語

本教程簡要介紹了Scrapy的使用,但是許多其他特性並沒有提及。

對於基本概念的瞭解,請訪問Basic concepts

我們推薦你繼續學習Scrapy項目的例子dirbot,你將從中受益更深,該項目包含本教程中提到的dmoz爬蟲。

Dirbot項目位於https://github.com/scrapy/dirbot

項目包含一個README文件,它詳細描述了項目的內容。

如果你熟悉git,你可以checkout它的源代碼。或者你可以通過點擊Downloads下載tarball或zip格式的文件。

另外這有一個代碼片斷共享網站,裏面共享內容包括爬蟲,中間件,擴展應用,腳本等。網站名字叫Scrapy snippets,有好的代碼要記得共享哦:-)


本教程的源代碼下載:http://files.cnblogs.com/txw1958/scrapy_tutorial.rar

scrapy實戰之定向抓取某網店商品資料

http://pythoner.org/wiki/64/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章