Scrapy是一個有着大量應用的可以用於爬取網站和提取結構化數據的程序框架,比如數據挖掘,信息處理。
雖然Scrapy最初設計用來做爬蟲,但是它也可以通過API來提取結構化數據。
如何實現一個簡單的爬蟲
爲了直觀的瞭解scrapy,我們通過最簡單的方法利用Scrapy Spider來實現一個爬蟲。
首先我們編寫一個用於爬取國外著名的類似知乎的網站 http://quotes.toscrape.com作爲示例,以下是相關代碼:
import scrapy
class QuotesSpider(scrapy.Spider):
name = 'quotes'
start_urls = [
'http://quotes.toscrape.com/tag/humor/',
]
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'author': quote.xpath('span/small/text()').get(),
'text': quote.css('span.text::text').get(),
}
next_page = response.css('li.next a::attr("href")').get()
if next_page is not None:
yield response.follow(next_page, self.parse)
這裏我推薦使用JetBrains推出的PyCharm作爲開發工具。具體怎麼新建項目就不介紹了,因爲專欄主要專注scrapy框架。如圖:
如果使用的是PyCharm可以直接運行,運行之後發現沒反應。我們可以使用命令行來運行一下試試,假設這段代碼已經保存爲demo.py文件,接下來我們使用scrapy的runspider命令來試試:
scrapy runspider demo.py -o quotes.json
當這個命令完成後,你會發現demo.py的相同目錄下多了一個quotes.json的文件,包含text和author字段,執行命令的截圖如下:
文件的內容格式如下:
[
{"author": "Jane Austen", "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"},
{"author": "Steve Martin", "text": "\u201cA day without sunshine is like, you know, night.\u201d"},
{"author": "Garrison Keillor", "text": "\u201cAnyone who thinks sitting in church can make you a Christian must also think that sitting in a garage can make you a car.\u201d"},
{"author": "Jim Henson", "text": "\u201cBeauty is in the eye of the beholder and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.\u201d"},
{"author": "Charles M. Schulz", "text": "\u201cAll you need is love. But a little chocolate now and then doesn't hurt.\u201d"},
{"author": "Suzanne Collins", "text": "\u201cRemember, we're madly in love, so it's all right to kiss me anytime you feel like it.\u201d"},
{"author": "Charles Bukowski", "text": "\u201cSome people never go crazy. What truly horrible lives they must lead.\u201d"},
{"author": "Terry Pratchett", "text": "\u201cThe trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.\u201d"},
{"author": "Dr. Seuss", "text": "\u201cThink left and think right and think low and think high. Oh, the thinks you can think up if only you try!\u201d"},
{"author": "George Carlin", "text": "\u201cThe reason I talk to myself is because I\u2019m the only one whose answers I accept.\u201d"},
{"author": "W.C. Fields", "text": "\u201cI am free of all prejudice. I hate everyone equally. \u201d"},
{"author": "Jane Austen", "text": "\u201cA lady's imagination is very rapid; it jumps from admiration to love, from love to matrimony in a moment.\u201d"}
]
爬蟲執行的過程
當你運行scrapy runspider demo.py -o quotes.json命令的時候,Scrapy根據爬蟲的定義通過爬蟲引擎運行。
爬蟲首先從start_urls屬性中的URL進行請求,並且調用默認的回調方法parse,將response對象當成一個參數傳遞進去。在parse回調中,我們使用一個CSS樣式進行遍歷,同是Python字典提取提問的text和author字段,接下來尋找下一頁的鏈接,並生成另外一個請求調用parse方法作爲回調。
這樣我們就瞭解到了一個特點,Scrapy框架的請求是定時的,而且是異步處理。這就意味着Scrapy在執行任務時不需要等待一個請求完成,甚至是處理完成,它可以同事發起另外一個請求或者做其他事情。這就意味着,及時有些請求失敗或者發生錯誤,其他的請求不妨礙執行。
除了能夠併發處理請求之外,Scrapy也允許你對爬蟲進行一些設置,比如下載延遲,限制每個域名或者IP的併發請求數量。甚至能自動的進行配置。
Scrapy還有哪些強大的功能
上面簡單的介紹了Scrapy如何從一個網站解析和存儲指定的字段,但這僅僅是Scrapy的冰山一角。Scrapy提供了大量的強大的特性來讓爬蟲更加容易和高效。比如:
- 內建的對HTML/XML數據解析的支持
- 交互式shell(IPython aware),在編寫和調試爬蟲時非常有用
- 內建的支持多種格式(Json,csv,XML)的支持以及在FTP或者本地等進行存儲
- 強大的擴展支持(中間件,擴展,管道)
- 大量內置的擴展和中間件用於處理以下內容
– cookies和session處理
– HTTP中的壓縮,認證,緩存等
– user-agent的僞造
– robots.txt
– 爬蟲約束
– 等等 - 一個Telnet的控制檯,用於爬蟲調試
等等等等。。。。
編寫運行爬蟲推薦買一個便宜的服務器,這裏推薦華爲雲,掃碼可以快速的進行註冊:
限時打折。