Scrapy是一個爲了爬取網站數據,提取結構性數據而編寫的應用框架。 其能夠應用在數據挖掘,信息處理或存儲歷史數據等一系列的程序中。其最初是爲了頁面抓取 (更確切來講, 網絡抓取 )所設計的, 也能夠應用在獲取API所返回的數據(例如 Amazon Associates Web Services ) 或者通用的網絡爬蟲。Scrapy用途普遍,能夠用於數據挖掘、監測和自動化測試。html
Scrapy 使用了 Twisted異步網絡庫來處理網絡通信。總體架構大體以下python
Scrapy主要包括瞭如下組件:windows
- 引擎(Scrapy)
用來處理整個系統的數據流, 觸發事務(框架核心) - 調度器(Scheduler)
用來接受引擎發過來的請求, 壓入隊列中, 並在引擎再次請求的時候返回. 能夠想像成一個URL(抓取網頁的網址或者說是連接)的優先隊列, 由它來決定下一個要抓取的網址是什麼, 同時去除重複的網址 - 下載器(Downloader)
用於下載網頁內容, 並將網頁內容返回給蜘蛛(Scrapy下載器是創建在twisted這個高效的異步模型上的) - 爬蟲(Spiders)
爬蟲是主要幹活的, 用於從特定的網頁中提取本身須要的信息, 即所謂的實體(Item)。用戶也能夠從中提取出連接,讓Scrapy繼續抓取下一個頁面 - 項目管道(Pipeline)
負責處理爬蟲從網頁中抽取的實體,主要的功能是持久化實體、驗證明體的有效性、清除不須要的信息。當頁面被爬蟲解析後,將被髮送到項目管道,並通過幾個特定的次序處理數據。 - 下載器中間件(Downloader Middlewares)
位於Scrapy引擎和下載器之間的框架,主要是處理Scrapy引擎與下載器之間的請求及響應。 - 爬蟲中間件(Spider Middlewares)
介於Scrapy引擎和爬蟲之間的框架,主要工做是處理蜘蛛的響應輸入和請求輸出。 - 調度中間件(Scheduler Middewares)
介於Scrapy引擎和調度之間的中間件,從Scrapy引擎發送到調度的請求和響應。
Scrapy運行流程大概以下:網絡
- 引擎從調度器中取出一個連接(URL)用於接下來的抓取
- 引擎把URL封裝成一個請求(Request)傳給下載器
- 下載器把資源下載下來,並封裝成應答包(Response)
- 爬蟲解析Response
- 解析出實體(Item),則交給實體管道進行進一步的處理
- 解析出的是連接(URL),則把URL交給調度器等待抓取
1、安裝架構
Linux:
併發
pip3 install scrapy
框架
Windows:pip install Twisted-18.9.0-cp36-cp36m-win_amd64.whl
1、安裝wheel pip install wheel 2、安裝Twisted https://www.lfd.uci.edu/~gohlke/pythonlibs/
3、安裝pywin32 https://sourceforge.net/projects/pywin32/files/ dom
4、安裝scrapy pip install scrapy異步
注:windows平臺須要依賴pywin32,請根據本身系統32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/ scrapy
2、爬蟲舉例
入門篇:美劇天堂前100最新(http://www.meijutt.com/new100.html)
一、建立工程
scrapy startproject movie
二、建立爬蟲程序
cd movie scrapy genspider meiju meijutt.com
三、自動建立目錄及文件
四、文件說明:
- scrapy.cfg 項目的配置信息,主要爲Scrapy命令行工具提供一個基礎的配置信息。(真正爬蟲相關的配置信息在settings.py文件中)
- items.py 設置數據存儲模板,用於結構化數據,如:Django的Model
- pipelines 數據處理行爲,如:通常結構化的數據持久化
- settings.py 配置文件,如:遞歸的層數、併發數,延遲下載等
- spiders 爬蟲目錄,如:建立文件,編寫爬蟲規則
注意:通常建立爬蟲文件時,以網站域名命名
五、設置數據存儲模板
items.py
import scrapy class MovieItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name = scrapy.Field()
六、編寫爬蟲
meiju.py
# -*- coding: utf-8 -*- import scrapy from movie.items import MovieItem class MeijuSpider(scrapy.Spider): name = "meiju" allowed_domains = ["meijutt.com"] start_urls = ['http://www.meijutt.com/new100.html'] def parse(self, response): movies = response.xpath('//ul[@class="top-list fn-clear"]/li') for each_movie in movies: item = MovieItem() item['name'] = each_movie.xpath('./h5/a/@title').extract()[0] yield item
七、設置配置文件
settings.py增長以下內容
ITEM_PIPELINES = {'movie.pipelines.MoviePipeline':100}
八、編寫數據處理腳本
pipelines.py
class MoviePipeline(object): def process_item(self, item, spider): with open("my_meiju.txt",'a') as fp: fp.write(item['name'].encode("utf8") + '\n')
九、執行爬蟲
cd movie scrapy crawl meiju --nolog
十、結果
進階篇:爬取校花網(http://www.xiaohuar.com/list-1-1.html)
一、建立一個工程
scrapy startproject pic
二、建立爬蟲程序
cd pic scrapy genspider xh xiaohuar.com
三、自動建立目錄及文件
四、文件說明:
- scrapy.cfg 項目的配置信息,主要爲Scrapy命令行工具提供一個基礎的配置信息。(真正爬蟲相關的配置信息在settings.py文件中)
- items.py 設置數據存儲模板,用於結構化數據,如:Django的Model
- pipelines 數據處理行爲,如:通常結構化的數據持久化
- settings.py 配置文件,如:遞歸的層數、併發數,延遲下載等
- spiders 爬蟲目錄,如:建立文件,編寫爬蟲規則
注意:通常建立爬蟲文件時,以網站域名命名
五、設置數據存儲模板
import scrapy class PicItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() addr = scrapy.Field() name = scrapy.Field()
六、編寫爬蟲
# -*- coding: utf-8 -*- import scrapy import os # 導入item中結構化數據模板 from pic.items import PicItem class XhSpider(scrapy.Spider): # 爬蟲名稱,惟一 name = "xh" # 容許訪問的域 allowed_domains = ["xiaohuar.com"] # 初始URL start_urls = ['http://www.xiaohuar.com/list-1-1.html'] def parse(self, response): # 獲取全部圖片的a標籤 allPics = response.xpath('//div[@class="img"]/a') for pic in allPics: # 分別處理每一個圖片,取出名稱及地址 item = PicItem() name = pic.xpath('./img/@alt').extract()[0] addr = pic.xpath('./img/@src').extract()[0] addr = 'http://www.xiaohuar.com'+addr item['name'] = name item['addr'] = addr # 返回爬取到的數據 yield item
七、設置配置文件
# 設置處理返回數據的類及執行優先級 ITEM_PIPELINES = {'pic.pipelines.PicPipeline':100}
八、編寫數據處理腳本
import urllib2 import os class PicPipeline(object): def process_item(self, item, spider): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0'} req = urllib2.Request(url=item['addr'],headers=headers) res = urllib2.urlopen(req) file_name = os.path.join(r'D:\my\down_pic',item['name']+'.jpg') with open(file_name,'wb') as fp: fp.write(res.read())
九、執行爬蟲
cd pic scrapy crawl xh --nolog
結果:
終極篇:我想要全部校花圖
註明:基於進階篇再修改成終極篇
# xh.py
# -*- coding: utf-8 -*-
import scrapy
import os
from scrapy.http import Request
# 導入item中結構化數據模板
from pic.items import PicItem
class XhSpider(scrapy.Spider):
# 爬蟲名稱,惟一
name = "xh"
# 容許訪問的域
allowed_domains = ["xiaohuar.com"]
# 初始URL
start_urls = ['http://www.xiaohuar.com/hua/']
# 設置一個空集合
url_set = set()
def parse(self, response):
# 若是圖片地址以http://www.xiaohuar.com/list-開頭,我才取其名字及地址信息
if response.url.startswith("http://www.xiaohuar.com/list-"):
allPics = response.xpath('//div[@class="img"]/a')
for pic in allPics:
# 分別處理每一個圖片,取出名稱及地址
item = PicItem()
name = pic.xpath('./img/@alt').extract()[0]
addr = pic.xpath('./img/@src').extract()[0]
addr = 'http://www.xiaohuar.com'+addr
item['name'] = name
item['addr'] = addr
# 返回爬取到的信息
yield item
# 獲取全部的地址連接
urls = response.xpath("//a/@href").extract()
for url in urls:
# 若是地址以http://www.xiaohuar.com/list-開頭且不在集合中,則獲取其信息
if url.startswith("http://www.xiaohuar.com/list-"):
if url in XhSpider.url_set:
pass
else:
XhSpider.url_set.add(url)
# 回調函數默認爲parse,也能夠經過from scrapy.http import Request來指定回調函數
# from scrapy.http import Request
# Request(url,callback=self.parse)
yield self.make_requests_from_url(url)
else:
pass