python爬蟲入門(六) Scrapy架構之原理介紹,pythonscrapy
Scrapy架構
Scrapy簡介
Scrapy是用純Python實現一個為了爬取網站資料、提取結構性資料而編寫的應用程式框架,用途非常廣泛。
架構的力量,使用者只需要定製開發幾個模組就可以輕鬆的實現一個爬蟲,用來抓取網頁內容以及各種圖片,非常之方便。
Scrapy 使用了 Twisted['twɪstɪd](其主要對手是Tornado)非同步網路架構來處理網路通訊,可以加快我們的下載速度,不用自己去實現非同步架構,並且包含了各種中介軟體介面,可以靈活的完成各種需求。
Scrapy架構
Scrapy Engine(引擎): 負責Spider、ItemPipeline、Downloader、Scheduler中間的通訊,訊號、資料傳遞等。
Scheduler(調度器): 它負責接受引擎發送過來的Request請求,並按照一定的方式進行整理排列,入隊,當引擎需要時,交還給引擎。
Downloader(下載器):負責下載Scrapy Engine(引擎)發送的所有Requests請求,並將其擷取到的Responses交還給Scrapy Engine(引擎),由引擎交給Spider來處理,
Spider(爬蟲):它負責處理所有Responses,從中分析提取資料,擷取Item欄位需要的資料,並將需要跟進的URL提交給引擎,再次進入Scheduler(調度器),
Item Pipeline(管道):它負責處理Spider中擷取到的Item,並進行進行後期處理(詳細分析、過濾、儲存等)的地方.
Downloader Middlewares(下載中介軟體):你可以當作是一個可以自訂擴充下載功能的組件。
Spider Middlewares(Spider中介軟體):你可以理解為是一個可以自定擴充和操作引擎和Spider中間通訊的功能組件(比如進入Spider的Responses;和從Spider出去的Requests)
白話講解Scrapy運作流程
代碼寫好,程式開始運行...
製作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 scrapyclass 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 scrapyclass ItcastItem(scrapy.Item): name = scrapy.Field() title = scrapy.Field() info = scrapy.Field()
(2)itcastspider.py
寫爬蟲程式
#!/usr/bin/env python# -*- coding:utf-8 -*-import scrapyfrom 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"的格式
管道檔案pipelines.py的用法
(1)setting.py修改
ITEM_PIPELINES = { #設定好在管道檔案裡寫的類 'mySpider.pipelines.ItcastPipeline': 300,}
(2)itcastspider.py
#!/usr/bin/env python# -*- coding:utf-8 -*-import scrapyfrom 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 jsonclass 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 scrapyclass ItcastItem(scrapy.Item): name = scrapy.Field() title = scrapy.Field() info = scrapy.Field()