scrapy爬蟲框架配置--settings


我們可以用一個settings.py做個簡單的介紹和解析:
例: ---->

# -*- coding: utf-8 -*-

# Scrapy settings for xigua project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'xigua' # Scrapy項目的名字,這將用來構造默認 User-Agent,同時也用來log,當您使用 startproject 命令創建項目時其也被自動賦值。

SPIDER_MODULES = ['xigua.spiders']  #Scrapy搜索spider的模塊列表 默認: [xxx.spiders]
NEWSPIDER_MODULE = 'xigua.spiders'  #使用 genspider 命令創建新spider的模塊。默認: 'xxx.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#爬取的默認User-Agent,除非被覆蓋
#USER_AGENT = 'xigua (+http://www.yourdomain.com)'

# Obey robots.txt rules
#如果啟用,Scrapy將會采用 robots.txt策略,常使用不遵循Flase
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#Scrapy downloader 並發請求(concurrent requests)的最大值,默認: 16
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
#未同意網站的請求配置延遲(默認為0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3  # 下載器延遲時間,下載器在同一網站面前需要等待的時間,該選項可以用來限制爬取速度,減輕服務器壓力。同時也支持小數:0.25 以秒為單# The download delay setting will honor only one of:
# 下載延遲設置,只能有一個生效
#CONCURRENT_REQUESTS_PER_DOMAIN = 16  # 對單個網站進行並發請求的最大值
#CONCURRENT_REQUESTS_PER_IP = 16  
#對單個ip進行並發請求的最大值,如果非0,則忽略,CONCURRENT_REQUESTS_PER_DOMAIN 設定,使用該設定。
#也就是說,並發限制將針對IP,而不是網站。該設定也影響 DOWNLOAD_DELAY: 如果 CONCURRENT_REQUESTS_PER_IP 非0,下載延遲應用在IP而不是網站上。


# Disable cookies (enabled by default)
# 禁用cookie(默認情況下啟用)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
# 禁用Telent控制台(默認啟用)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
# 覆蓋默認請求標頭,也可以加入請求頭,獲取同樣來自開發着工具,
# 很多網站都會檢查客戶端的headers,比如豆瓣就是每一個請求都檢查headers的user_agent,否則只會返回403,可以開啟 USER_AGENT 請求頭
#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://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'xigua.middlewares.XiguaSpiderMiddleware': 543,
#}


# Enable or disable downloader middlewares
# 啟用或禁用下載器中間件
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'xigua.middlewares.XiguaDownloaderMiddleware': 543,
#}

# Enable or disable extensions
#啟用或禁用擴展程序
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# 配置項目管道,如下載圖片的圖片管道,分布式爬蟲多爬蟲的pipeline,結尾int值是優先級,可以理解為權重,以逗號間隔,是個集合
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'xigua.pipelines.XiguaPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# 啟用或配置AutoThrottle擴展(默認情況下禁用)
# See https://doc.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
# Scrapy請求的平均數量應該並行發送每個遠程服務器
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# 啟用顯示所收到的每個響應的調節統計信息
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# 啟用或配置 Http 緩存(默認情況下禁用)
# See https://doc.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'


這就是一個完整的setting.py的接本情況:
接下來再來詳細看看,並且還有哪些可以配置的呢?
-----》

#-----------------------日志文件配置----------------------------------- # 默認: True,是否啟用logging。 # LOG_ENABLED=True # 默認: 'utf-8',logging使用的編碼。 # LOG_ENCODING='utf-8' # 它是利用它的日志信息可以被格式化的字符串。默認值:'%(asctime)s [%(name)s] %(levelname)s: %(message)s' # LOG_FORMAT='%(asctime)s [%(name)s] %(levelname)s: %(message)s' # 它是利用它的日期/時間可以格式化字符串。默認值: '%Y-%m-%d %H:%M:%S' # LOG_DATEFORMAT='%Y-%m-%d %H:%M:%S' #日志文件名 #LOG_FILE = "dg.log" #日志文件級別,默認值:“DEBUG”,log的最低級別。可選的級別有: CRITICAL、 ERROR、WARNING、INFO、DEBUG 。 LOG_LEVEL = 'WARNING'

# -----------------------------robots協議--------------------------------------------- # Obey robots.txt rules # robots.txt 是遵循 Robot協議 的一個文件,它保存在網站的服務器中,它的作用是,告訴搜索引擎爬蟲, # 本網站哪些目錄下的網頁 不希望 你進行爬取收錄。在Scrapy啟動后,會在第一時間訪問網站的 robots.txt 文件, # 然后決定該網站的爬取范圍。 # ROBOTSTXT_OBEY = True # 對於失敗的HTTP請求(如超時)進行重試會降低爬取效率,當爬取目標基數很大時,舍棄部分數據不影響大局,提高效率 RETRY_ENABLED = False #請求下載超時時間,默認180秒 DOWNLOAD_TIMEOUT=20 # 這是響應的下載器下載的最大尺寸,默認值:1073741824 (1024MB) # DOWNLOAD_MAXSIZE=1073741824 # 它定義為響應下載警告的大小,默認值:33554432 (32MB) # DOWNLOAD_WARNSIZE=33554432

# ------------------------全局並發數的一些配置:------------------------------- # Configure maximum concurrent requests performed by Scrapy (default: 16) # 默認 Request 並發數:16 # CONCURRENT_REQUESTS = 32 # 默認 Item 並發數:100 # CONCURRENT_ITEMS = 100 # The download delay setting will honor only one of: # 默認每個域名的並發數:8 #CONCURRENT_REQUESTS_PER_DOMAIN = 16 # 每個IP的最大並發數:0表示忽略 # CONCURRENT_REQUESTS_PER_IP = 0 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY 會影響 CONCURRENT_REQUESTS,不能使並發顯現出來,設置下載延遲 #DOWNLOAD_DELAY = 3 # Disable cookies (enabled by default) #禁用cookies,有些站點會從cookies中判斷是否為爬蟲 # COOKIES_ENABLED = True # COOKIES_DEBUG = True # Crawl responsibly by identifying yourself (and your website) on the user-agent # 它定義了在抓取網站所使用的用戶代理,默認值:“Scrapy / VERSION“ #USER_AGENT = ' (+http://www.yourdomain.com)' # 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 http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html SPIDER_MIDDLEWARES = { 'companyNews.middlewares.UserAgentmiddleware': 401, 'companyNews.middlewares.ProxyMiddleware':426, } # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = { 'companyNews.middlewares.UserAgentmiddleware': 400, 'companyNews.middlewares.ProxyMiddleware':425, # 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware':423, # 'companyNews.middlewares.CookieMiddleware': 700, } MYEXT_ENABLED=True # 開啟擴展 IDLE_NUMBER=12 # 配置空閑持續時間單位為 360個 ,一個時間單位為5s # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html # 在 EXTENSIONS 配置,激活擴展 EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, 'companyNews.extensions.RedisSpiderSmartIdleClosedExensions': 500, } # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html # 注意:自定義pipeline的優先級需高於Redispipeline,因為RedisPipeline不會返回item, # 所以如果RedisPipeline優先級高於自定義pipeline,那么自定義pipeline無法獲取到item ITEM_PIPELINES = { #將清除的項目在redis進行處理,# 將RedisPipeline注冊到pipeline組件中(這樣才能將數據存入Redis) # 'scrapy_redis.pipelines.RedisPipeline': 400, 'companyNews.pipelines.companyNewsPipeline': 300,# 自定義pipeline視情況選擇性注冊(可選) } # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings

# ----------------scrapy默認已經自帶了緩存,配置如下----------------- # 打開緩存 #HTTPCACHE_ENABLED = True # 設置緩存過期時間(單位:秒) #HTTPCACHE_EXPIRATION_SECS = 0 # 緩存路徑(默認為:.scrapy/httpcache) #HTTPCACHE_DIR = 'httpcache' # 忽略的狀態碼 #HTTPCACHE_IGNORE_HTTP_CODES = [] # HTTPERROR_ALLOWED_CODES = [302, 301] # 緩存模式(文件緩存) #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

#-----------------Scrapy-Redis分布式爬蟲相關設置如下-------------------------- # Enables scheduling storing requests queue in redis. #啟用Redis調度存儲請求隊列,使用Scrapy-Redis的調度器,不再使用scrapy的調度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # Ensure all spiders share same duplicates filter through redis. #確保所有的爬蟲通過Redis去重,使用Scrapy-Redis的去重組件,不再使用scrapy的去重組件 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 默認請求序列化使用的是pickle 但是我們可以更改為其他類似的。PS:這玩意兒2.X的可以用。3.X的不能用 # SCHEDULER_SERIALIZER = "scrapy_redis.picklecompat" # 使用優先級調度請求隊列 (默認使用), # 使用Scrapy-Redis的從請求集合中取出請求的方式,三種方式擇其一即可: # 分別按(1)請求的優先級/(2)隊列FIFO/(先進先出)(3)棧FILO 取出請求(先進后出) # SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.PriorityQueue' # 可選用的其它隊列 SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.FifoQueue' # SCHEDULER_QUEUE_CLASS = 'scrapy_redis.queue.LifoQueue' # Don't cleanup redis queues, allows to pause/resume crawls. #不清除Redis隊列、這樣可以暫停/恢復 爬取, # 允許暫停,redis請求記錄不會丟失(重啟爬蟲不會重頭爬取已爬過的頁面) #SCHEDULER_PERSIST = True

#----------------------redis的地址配置------------------------------------- # Specify the full Redis URL for connecting (optional). # If set, this takes precedence over the REDIS_HOST and REDIS_PORT settings. # 指定用於連接redis的URL(可選) # 如果設置此項,則此項優先級高於設置的REDIS_HOST 和 REDIS_PORT # REDIS_URL = 'redis://root:密碼@主機IP:端口' # REDIS_URL = 'redis://root:123456@192.168.8.30:6379' REDIS_URL = 'redis://root:%s@%s:%s'%(password_redis,host_redis,port_redis) # 自定義的redis參數(連接超時之類的) REDIS_PARAMS={'db': db_redis} # Specify the host and port to use when connecting to Redis (optional). # 指定連接到redis時使用的端口和地址(可選) #REDIS_HOST = '127.0.0.1' #REDIS_PORT = 6379 #REDIS_PASS = '19940225'
#-----------------------------------------暫時用不到------------------------------------------------------- # 它定義了將被允許抓取的網址的長度為URL的最大極限,默認值:2083 # URLLENGTH_LIMIT=2083 # 爬取網站最大允許的深度(depth)值,默認值0。如果為0,則沒有限制 # DEPTH_LIMIT = 3 # 整數值。用於根據深度調整request優先級。如果為0,則不根據深度進行優先級調整。 # DEPTH_PRIORITY=3 # 最大空閑時間防止分布式爬蟲因為等待而關閉 # 這只有當上面設置的隊列類是SpiderQueue或SpiderStack時才有效 # 並且當您的蜘蛛首次啟動時,也可能會阻止同一時間啟動(由於隊列為空) # SCHEDULER_IDLE_BEFORE_CLOSE = 10 # 序列化項目管道作為redis Key存儲 # REDIS_ITEMS_KEY = '%(spider)s:items' # 默認使用ScrapyJSONEncoder進行項目序列化 # You can use any importable path to a callable object. # REDIS_ITEMS_SERIALIZER = 'json.dumps' # 自定義redis客戶端類 # REDIS_PARAMS['redis_cls'] = 'myproject.RedisClient' # 如果為True,則使用redis的'spop'進行操作。 # 如果需要避免起始網址列表出現重復,這個選項非常有用。開啟此選項urls必須通過sadd添加,否則會出現類型錯誤。 # REDIS_START_URLS_AS_SET = False # RedisSpider和RedisCrawlSpider默認 start_usls 鍵 # REDIS_START_URLS_KEY = '%(name)s:start_urls' # 設置redis使用utf-8之外的編碼 # REDIS_ENCODING = 'latin1' # Disable Telnet Console (enabled by default) # 它定義是否啟用telnetconsole,默認值:True #TELNETCONSOLE_ENABLED = False # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.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
最后再來兩條啟用調試的命令:
啟用調試工具 命令行調試 scrapy shell url 查看網頁,不過這種方式可能對於要請求頭的網頁不行,對於一般的網頁還是可以的 scrapy view shell 用來查看動態加載的網頁,如果查看的網頁用了動態加載,那么用這個命令行打開的網頁就是不完整的,肯定缺少了什么

暫停和恢復爬蟲
初學者最頭疼的事情就是沒有處理好異常,當爬蟲爬到一半的時候突然因為錯誤而中斷了,但是這時又不能從中斷的地方開始繼續爬,頓時感覺心里日了狗,但是這里有一個方法可以暫時的存儲你爬的狀態,當爬蟲中斷的時候繼續打開后依然可以從中斷的地方爬,不過雖說持久化可以有效的處理,但是要注意的是當使用cookie臨時的模擬登錄狀態的時候要注意cookie的有效期

只需要在setting.py中JOB_DIR=file_name 其中填的是你的文件目錄,注意這里的目錄不允許共享,只能存儲單獨的一個spdire的運行狀態,如果你不想在從中斷的地方開始運行,只需要將這個文件夾刪除即可

當然還有其他的放法:scrapy crawl somespider -s JOBDIR=crawls/somespider-1,這個是在終端啟動爬蟲的時候調用的,可以通過ctr+c中斷,恢復還是輸入上面的命令


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM