Scrapy筆記01- 入門篇
Scrapy是一個爲了爬取網站數據,提取結構性數據而編寫的應用框架。能夠應用在包括數據挖掘, 信息處理或存儲歷史數據等一系列的程序中。其最初是爲了頁面抓取(更確切來講,網絡抓取)所設計的, 也能夠應用在獲取API所返回的數據(好比Web Services)或者通用的網絡爬蟲。
Scrapy也能幫你實現高階的爬蟲框架,好比爬取時的網站認證、內容的分析處理、重複抓取、分佈式爬取等等很複雜的事。css
安裝scrapy
個人測試環境是centos6.5html
升級python到最新版的2.7,下面的全部步驟都切換到root用戶java
因爲scrapy目前只能運行在python2上,因此先更新centos上面的python到最新的 Python 2.7.11, 具體方法請google下不少這樣的教程。python
先安裝一些依賴軟件
yum install python-devel
yum install libffi-devel
yum install openssl-devel
而後安裝pyopenssl庫
安裝xlml
yum install python-lxml
yum install libxml2-devel
yum install libxslt-devel
安裝service-identity
pip install service-identity
安裝twisted
安裝scrapy
測試scrapy
最終成功,太不容易了! c++
簡單示例
建立一個python源文件,名爲stackoverflow.py,內容以下:git
import scrapy
class StackOverflowSpider(scrapy.Spider):
name = 'stackoverflow'
start_urls = ['http://stackoverflow.com/questions?sort=votes']
def parse(self, response):
for href in response.css('.question-summary h3 a::attr(href)'):
full_url = response.urljoin(href.extract())
yield scrapy.Request(full_url, callback=self.parse_question)
def parse_question(self, response):
yield {
'title': response.css('h1 a::text').extract()[0],
'votes': response.css('.question .vote-count-post::text').extract()[0],
'body': response.css('.question .post-text').extract()[0],
'tags': response.css('.question .post-tag::text').extract(),
'link': response.url,
}
運行:正則表達式
scrapy runspider stackoverflow_spider.py -o top-stackoverflow-questions.json
結果相似下面:shell
[{
"body": "... LONG HTML HERE ...",
"link": "http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array",
"tags": ["java", "c++", "performance", "optimization"],
"title": "Why is processing a sorted array faster than an unsorted array?",
"votes": "9924"
},
{
"body": "... LONG HTML HERE ...",
"link": "http://stackoverflow.com/questions/1260748/how-do-i-remove-a-git-submodule",
"tags": ["git", "git-submodules"],
"title": "How do I remove a Git submodule?",
"votes": "1764"
},
...]
當你運行scrapy runspider somefile.py
這條語句的時候,Scrapy會去尋找源文件中定義的一個spider而且交給爬蟲引擎來執行它。 start_urls
屬性定義了開始的URL,爬蟲會經過它來構建初始的請求,返回response後再調用默認的回調方法parse
並傳入這個response。 咱們在parse
回調方法中經過使用css選擇器提取每一個提問頁面連接的href屬性值,而後yield
另一個請求, 並註冊parse_question
回調方法,在這個請求完成後被執行。 數據庫
處理流程圖:json
![scrapy架構圖](http://static.javashuo.com/static/loading.gif)
Scrapy的一個好處是全部請求都是被調度並異步處理,就算某個請求出錯也不影響其餘請求繼續被處理。
咱們的示例中將解析結果生成json格式,你還能夠導出爲其餘格式(好比XML、CSV),或者是將其存儲到FTP、Amazon S3上。 你還能夠經過pipeline 將它們存儲到數據庫中去,這些數據保存的方式各類各樣。
Scrapy特性一覽
你已經能夠經過Scrapy從一個網站上面爬取數據並將其解析保存下來了,可是這只是Scrapy的皮毛。 Scrapy提供了更多的特性來讓你爬取更加容易和高效。好比:
- 內置支持擴展的CSS選擇器和XPath表達式來從HTML/XML源碼中選擇並提取數據,還能使用正則表達式
- 提供交互式shell控制檯試驗CSS和XPath表達式,這個在調試你的蜘蛛程序時頗有用
- 內置支持生成多種格式的訂閱導出(JSON、CSV、XML)並將它們存儲在多個位置(FTP、S三、本地文件系統)
- 健壯的編碼支持和自動識別,用於處理外文、非標準和錯誤編碼問題
- 可擴展,容許你使用signals 和友好的API(middlewares, extensions, 和pipelines)來編寫自定義插件功能。
- 大量的內置擴展和中間件供使用:
- cookies and session handling
- HTTP features like compression, authentication, caching
- user-agent spoofing
- robots.txt
- crawl depth restriction
- and more
- 還有其餘好多好東東,好比可重複利用蜘蛛來爬取Sitemaps和XML/CSV訂閱, 一個跟爬取元素關聯的媒體管道來 自動下載圖片, 一個緩存DNS解析器等等。