特點:
- scrapy利用twisted的設(shè)計實現(xiàn)了非阻塞的異步操作。這相比于傳統(tǒng)的阻塞式請求,極大的提高了CPU的使用率,以及爬取效率。
- 配置簡單,可以簡單的通過設(shè)置一行代碼實現(xiàn)復(fù)雜功能。
- 可拓展,插件豐富,比如分布式scrapy + redis、爬蟲可視化等插件。
- 解析方便易用,scrapy封裝了xpath等解析器,提供了更方便更高級的selector構(gòu)造器,可有效的處理破損的HTML代碼和編碼。
一:scrapy安裝
pip install scrapy -i https://pypi.douban.com/simple
pip install twisted -i https://pypi.douban.com/simple
二:框架導(dǎo)圖:

三:組件介紹
| 組件 | 作用 | |
|---|---|---|
| Scrapy Engine(引擎) | 負責(zé)Spider、ItemPipeline、Downloader、Scheduler中間的通訊,信號、數(shù)據(jù)傳遞等 | 已實現(xiàn) |
| Scheduler(調(diào)度器) | 它負責(zé)接受引擎發(fā)送過來的Request請求,并按照一定的方式進行整理排列,入隊,當(dāng)引擎需要時,交還給引擎 | 已實現(xiàn) |
| Downloader(下載器) | 負責(zé)下載(引擎)發(fā)送的所有Requests請求,并將其獲取到的Responses交還給Scrapy Engine(引擎),由引擎交給Spider來處理。 | 已實現(xiàn) |
| Spider(爬蟲) | 它負責(zé)處理所有Responses,從中分析提取數(shù)據(jù),獲取Item字段需要的數(shù)據(jù),并將需要跟進的URL提交給引擎,再次進入Scheduler | 需要手寫 |
| Item Pipeline(管道) | 它負責(zé)處理Spider中獲取到的Item,并進行進行后期處理(詳細分析、過濾、存儲等)的地方 | 需要手寫 |
| Downloader Middlewares下載中間件 | 一個可以自定義擴展下載功能的組件。 | 一般不用手寫 |
| Spider Middlewares(Spider中間件) | 一個可以自定擴展和操作引擎和Spider中間通信的功能組件 | 一般不用手寫 |
四:運行流程
第一步:
- 引擎:Hi!Spider, 你要處理哪一個網(wǎng)站?
- Spider:老大要我處理xxxx.com。
- 引擎:你把第一個需要處理的URL給我吧。
- Spider:給你,第一個URL是xxxxxxx.com。
第二步:
- 引擎:Hi!調(diào)度器,我這有request請求你幫我排序入隊一下。
- 調(diào)度器:好的,正在處理你等一下。
- 引擎:Hi!調(diào)度器,把你處理好的request請求給我。
- 調(diào)度器:給你,這是我處理好的request
第三步:
- 引擎:Hi!下載器,你按照老大的下載中間件的設(shè)置幫我下載一下這個request請求
- 下載器:好的!給你,這是下載好的東西。(如果失敗:sorry,這個request下載失敗了。然后引擎告訴調(diào)度器,這個request下載失敗了,你記錄一下,我們待會兒再下載)
第四步:
- 引擎:Hi!Spider,這是下載好的東西,并且已經(jīng)按照老大的下載中間件處理過了,你自己處理一下(注意!這兒responses默認是交給def parse()這個函數(shù)處理的)
- Spider:Hi!引擎,我這里有兩個結(jié)果,這個是我需要跟進的URL,還有這個是我獲取到的需要存儲的Item數(shù)據(jù)。
第五步:
- 引擎:Hi! 管道 我這兒有個item你幫我處理一下。 調(diào)度器!這是需要跟進URL你幫我處理下。然后從第二回合開始循環(huán),直到獲取完老大需要全部信息。
- 管道調(diào)度器:好的,現(xiàn)在就做!
五:搭建一個scrapy項目(項目初始化)
- 創(chuàng)建一個scrapy項目
scrapy startproject name # name 為項目名稱 - 創(chuàng)建一個spider
cd name # 進入創(chuàng)建的項目
scrapy genspider spider_name url # spider_name為爬蟲名,url為要抓取的目標(biāo)網(wǎng)站
scrapy crawl spider_name # 執(zhí)行爬蟲 - spider介紹
點擊查看代碼
import scrapy
class BdSpiderSpider(scrapy.Spider):
name = 'spider_name'
allowed_domains = ['baidu.com']
start_urls = ['https://www.baidu.com']
def parse(self, response,**kwargs):
pass
- name:標(biāo)識spider。它在一個項目中必須是唯一的,即不能為不同的爬行器設(shè)置相同的名稱
- allowed_domains:允許爬取url的域名
- start_urls:一個url列表,spider從這些網(wǎng)頁開始抓取
- parse():一個方法,當(dāng)start_urls里面的網(wǎng)頁抓取下來之后需要調(diào)用這個方法解析網(wǎng)頁內(nèi)容
- items
點擊查看代碼
import scrapy
class MySpiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
- items用于定義抓取的字段名
- pipeline
點擊查看代碼
from itemadapter import ItemAdapter
class MySpiderPipeline:
def process_item(self, item, spider):
return item
- 數(shù)據(jù)的存儲,本地或者數(shù)據(jù)庫
- settings(具體看下面注釋)
點擊查看代碼
# Scrapy settings for my_spider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'my_spider'
SPIDER_MODULES = ['my_spider.spiders']
NEWSPIDER_MODULE = 'my_spider.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.71'
# Obey robots.txt rules
# robots協(xié)議,默認遵守
ROBOTSTXT_OBEY = False
# 日志等級,ERROR最高
LOG_LEVEL = "ERROR"
# Configure maximum concurrent requests performed by Scrapy (default: 16)
# 并發(fā)請求(concurrent requests)的最大值
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# 下載延遲
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# 對單個網(wǎng)站進行并發(fā)請求的最大值
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
# 對單個IP進行并發(fā)請求的最大值。如果非0,則忽略
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
# COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
# }
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'my_spider.middlewares.MySpiderSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'my_spider.middlewares.MySpiderDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
# 優(yōu)先級 數(shù)字越小,越靠近管道
'my_spider.pipelines.MySpiderPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
浙公網(wǎng)安備 33010602011771號