XPath expression提取
//div[@id='specifications']/p[2]/text()[2]
如果要了解更多的XPath 參考這裡 XPath reference.
蜘蛛代碼如下:
class MininovaSpider(CrawlSpider): name = '參考閱讀4' allowed_domains = ['參考閱讀4'] start_urls = ['參考閱讀1'] rules = [Rule(SgmlLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')] def parse_torrent(self, response): x = HtmlXPathSelector(response) torrent = TorrentItem() torrent['url'] = response.url torrent['name'] = x.select("//h1/text()").extract() torrent['description'] = x.select("//div[@id='description']").extract() torrent['size'] = x.select("//div[@id='info-left']/p[2]/text()[2]").extract() yield torrent
因為很簡單的原因,我們有意把重要的數據定義放在了上面。
運行蜘蛛來抓取數據
我們需要創建一個運行文件,放在setting同級目錄下,用來單獨運行蜘蛛:
from scrapy.cmdline import executeexecute('scrapy crawl 所創建的py文件名'.split())
最後,運行這個文件,可以看到相應的數據就輸出了出來。
查看一下數據:scraped_data.json。
關注一下數據,你會發現,所有欄位都是lists(除了url是直接賦值),這是因為selectors返回的就是lists格式,如果你想存儲單獨數據或者在數據上增加一些解釋或者清洗,可以使用Item Loaders
你也看到了如何使用Scrapy從一個網站提取和存儲數據,實際上,Scrapy提供了許多強大的特性,讓它更容易和高效的抓取:
1>內建 selecting and extracting,支持從HTML,XML提取數據
2>內建Item Loaders,支持數據清洗和過濾消毒,使用預定義的一個
過濾器集合,可以在所有蜘蛛間公用
3>內建多格式generating
feed exports支持(JSON,
CSV, XML),可以在後端存儲為多種方式(
FTP,
S3, local filesystem)
4>針對抓取對象,具有自動圖像(或者任何其他媒體)下載automatically downloading images的管道線
5>支持擴展抓取extending Scrap,使用signals來自定義插入
函數或者定義好的API(middlewares, extensions, and pipelines)
6>大範圍的內建中間件和擴展,基於但不限於
cookies and session handling
HTTP compression
HTTP authentication
HTTP cache
user-agent spoofing
robots.txt
crawl depth restriction
and more
7>強壯的編碼支持和自動識別機制,可以處理多種國外的、非標準的、不完整的編碼聲明等等
8>可擴展的統計採集stats collection,針對數十個採集蜘蛛,在監控蜘蛛性能和識別斷線斷路?方面很有用處
9>一個可交互的XPaths腳本命令平台介面Interactive shell console,在調試撰寫蜘蛛上是非常有用
10>一個系統服務級別的設計,可以在產品中非常容易的部署和運行你的蜘蛛
11>內建的Web service,可以監視和控制你的機器人
12>一個
Telnet控制台Telnet console,可以鉤入一個Python的控制台在你的抓取進程中,以便內視或者調試你的爬蟲
14>具備緩存DNS和resolver功能