Scrapy簡介html
Scrapy是用純Python實現一個爲了爬取網站數據、提取結構性數據而編寫的應用框架,用途很是普遍。python
框架的力量,用戶只須要定製開發幾個模塊就能夠輕鬆的實現一個爬蟲,用來抓取網頁內容以及各類圖片,很是之方便。android
Scrapy 使用了 Twisted['twɪstɪd]
(其主要對手是Tornado)異步網絡框架來處理網絡通信,能夠加快咱們的下載速度,不用本身去實現異步框架,而且包含了各類中間件接口,能夠靈活的完成各類需求。數據庫
Scrapy架構json
Scrapy Engine(引擎)
: 負責Spider
、ItemPipeline
、Downloader
、Scheduler
中間的通信,信號、數據傳遞等。網絡
Scheduler(調度器)
: 它負責接受引擎
發送過來的Request請求,並按照必定的方式進行整理排列,入隊,當引擎
須要時,交還給引擎
。架構
Downloader(下載器)
:負責下載Scrapy Engine(引擎)
發送的全部Requests請求,並將其獲取到的Responses交還給Scrapy Engine(引擎)
,由引擎
交給Spider
來處理,app
Spider(爬蟲)
:它負責處理全部Responses,從中分析提取數據,獲取Item字段須要的數據,並將須要跟進的URL提交給引擎
,再次進入Scheduler(調度器)
,框架
Item Pipeline(管道)
:它負責處理Spider
中獲取到的Item,並進行進行後期處理(詳細分析、過濾、存儲等)的地方.dom
Downloader Middlewares(下載中間件)
:你能夠看成是一個能夠自定義擴展下載功能的組件。
Spider Middlewares(Spider中間件)
:你能夠理解爲是一個能夠自定擴展和操做引擎
和Spider
中間通訊
的功能組件(好比進入Spider
的Responses;和從Spider
出去的Requests)
白話講解Scrapy運做流程
代碼寫好,程序開始運行...
引擎
:Hi!Spider
, 你要處理哪個網站?
Spider
:老大要我處理xxxx.com。
引擎
:你把第一個須要處理的URL給我吧。
Spider
:給你,第一個URL是xxxxxxx.com。
引擎
:Hi!調度器
,我這有request請求你幫我排序入隊一下。
調度器
:好的,正在處理你等一下。
引擎
:Hi!調度器
,把你處理好的request請求給我。
調度器
:給你,這是我處理好的request
引擎
:Hi!下載器,你按照老大的下載中間件
的設置幫我下載一下這個request請求
下載器
:好的!給你,這是下載好的東西。(若是失敗:sorry,這個request下載失敗了。而後引擎
告訴調度器
,這個request下載失敗了,你記錄一下,咱們待會兒再下載)
引擎
:Hi!Spider
,這是下載好的東西,而且已經按照老大的下載中間件
處理過了,你本身處理一下(注意!這兒responses默認是交給def parse()
這個函數處理的)
Spider
:(處理完畢數據以後對於須要跟進的URL),Hi!引擎
,我這裏有兩個結果,這個是我須要跟進的URL,還有這個是我獲取到的Item數據。
引擎
:Hi !管道
我這兒有個item你幫我處理一下!調度器
!這是須要跟進URL你幫我處理下。而後從第四步開始循環,直到獲取完老大須要所有信息。
管道``調度器
:好的,如今就作!
製做Scrapy爬蟲步驟
1.新建項目
scrapy startproject mySpider
scrapy.cfg :項目的配置文件 mySpider/ :項目的Python模塊,將會從這裏引用代碼 mySpider/items.py :項目的目標文件 mySpider/pipelines.py :項目的管道文件 mySpider/settings.py :項目的設置文件 mySpider/spiders/ :存儲爬蟲代碼目錄
2.明確目標(mySpider/items.py)
想要爬取哪些信息,在Item裏面定義結構化數據字段,保存爬取到的數據
3.製做爬蟲(spiders/xxxxSpider.py)
import scrapy class ItcastSpider(scrapy.Spider): name = "itcast" allowed_domains = ["itcast.cn"] start_urls = ( 'http://www.itcast.cn/', ) def parse(self, response): pass
name = ""
:這個爬蟲的識別名稱,必須是惟一的,在不一樣的爬蟲必須定義不一樣的名字。
allow_domains = []
是搜索的域名範圍,也就是爬蟲的約束區域,規定爬蟲只爬取這個域名下的網頁,不存在的URL會被忽略。
start_urls = ()
:爬取的URL元祖/列表。爬蟲從這裏開始抓取數據,因此,第一次下載的數據將會從這些urls開始。其餘子URL將會從這些起始URL中繼承性生成。
parse(self, response)
:解析的方法,每一個初始URL完成下載後將被調用,調用的時候傳入從每個URL傳回的Response對象來做爲惟一參數,主要做用以下:
4.保存數據(pipelines.py)
在管道文件裏面設置保存數據的方法,能夠保存到本地或數據庫
舒適提醒
第一次運行scrapy項目的時候
出現-->"DLL load failed" 錯誤提示,須要安裝pypiwin32模塊
(1)items.py
想要爬取的信息
# -*- coding: utf-8 -*- import scrapy class ItcastItem(scrapy.Item): name = scrapy.Field() title = scrapy.Field() info = scrapy.Field()
(2)itcastspider.py
寫爬蟲程序
#!/usr/bin/env python # -*- coding:utf-8 -*- import scrapy from mySpider.items import ItcastItem # 建立一個爬蟲類 class ItcastSpider(scrapy.Spider): # 爬蟲名 name = "itcast" # 容許爬蟲做用的範圍 allowd_domains = ["http://www.itcast.cn/"] # 爬蟲起始的url start_urls = [ "http://www.itcast.cn/channel/teacher.shtml#", ] def parse(self, response): teacher_list = response.xpath('//div[@class="li_txt"]') # 全部老師信息的列表集合 teacherItem = [] # 遍歷根節點集合 for each in teacher_list: # Item對象用來保存數據的 item = ItcastItem() # name, extract() 將匹配出來的結果轉換爲Unicode字符串 # 不加extract() 結果爲xpath匹配對象 name = each.xpath('./h3/text()').extract() # title title = each.xpath('./h4/text()').extract() # info info = each.xpath('./p/text()').extract() item['name'] = name[0].encode("gbk") item['title'] = title[0].encode("gbk") item['info'] = info[0].encode("gbk") teacherItem.append(item) return teacherItem
輸入命令:scrapy crawl itcast -o itcast.csv 保存爲 ".csv"的格式
(1)setting.py修改
ITEM_PIPELINES = { #設置好在管道文件裏寫的類 'mySpider.pipelines.ItcastPipeline': 300, }
(2)itcastspider.py
#!/usr/bin/env python # -*- coding:utf-8 -*- import scrapy from mySpider.items import ItcastItem # 建立一個爬蟲類 class ItcastSpider(scrapy.Spider): # 爬蟲名 name = "itcast" # 容許爬蟲做用的範圍 allowd_domains = ["http://www.itcast.cn/"] # 爬蟲其實的url start_urls = [ "http://www.itcast.cn/channel/teacher.shtml#aandroid", ] def parse(self, response): #with open("teacher.html", "w") as f: # f.write(response.body) # 經過scrapy自帶的xpath匹配出全部老師的根節點列表集合 teacher_list = response.xpath('//div[@class="li_txt"]') # 遍歷根節點集合 for each in teacher_list: # Item對象用來保存數據的 item = ItcastItem() # name, extract() 將匹配出來的結果轉換爲Unicode字符串 # 不加extract() 結果爲xpath匹配對象 name = each.xpath('./h3/text()').extract() # title title = each.xpath('./h4/text()').extract() # info info = each.xpath('./p/text()').extract() item['name'] = name[0] item['title'] = title[0] item['info'] = info[0] yield item
(3)pipelines.py
數據保存到本地
# -*- coding: utf-8 -*- import json class ItcastPipeline(object): # __init__方法是可選的,作爲類的初始化方法 def __init__(self): # 建立了一個文件 self.filename = open("teacher.json", "w") # process_item方法是必須寫的,用來處理item數據 def process_item(self, item, spider): jsontext = json.dumps(dict(item), ensure_ascii = False) + "\n" self.filename.write(jsontext.encode("utf-8")) return item # close_spider方法是可選的,結束時調用這個方法 def close_spider(self, spider): self.filename.close()
(4)items.py
# -*- coding: utf-8 -*- import scrapy class ItcastItem(scrapy.Item): name = scrapy.Field() title = scrapy.Field() info = scrapy.Field()