文件目錄說明:
scrapy.cfg: 項目的配置文件
tutorial/: 該項目的python模塊翩活。之后您將在此加入代碼。
tutorial/items.py: 項目中的item文件.
tutorial/pipelines.py: 項目中的pipelines文件.
tutorial/settings.py: 項目的設(shè)置文件.
tutorial/spiders/: 放置spider代碼的目錄.
定義item
Item 是保存爬取到的數(shù)據(jù)的容器惊暴;其使用方法和python字典類似, 并且提供了額外保護機制來避免拼寫錯誤導(dǎo)致的未定義字段錯誤。
示例代碼:
import scrapy
class DmozItem(scrapy.Item):
? ? title = scrapy.Field()
? ? link = scrapy.Field()
? ? desc = scrapy.Field()
定義spider
name: 用于區(qū)別Spider焰轻。 該名字必須是唯一的数苫,您不可以為不同的Spider設(shè)定相同的名字聪舒。
start_urls: 包含了Spider在啟動時進行爬取的url列表。 因此虐急,第一個被獲取到的頁面將是其中之一箱残。 后續(xù)的URL則從初始的URL獲取到的數(shù)據(jù)中提取。
parse() :是spider的一個方法。 被調(diào)用時被辑,每個初始URL完成下載后生成的 Response 對象將會作為唯一的參數(shù)傳遞給該函數(shù)燎悍。 該方法負(fù)責(zé)解析返回的數(shù)據(jù)(response data),提取數(shù)據(jù)(生成item)以及生成需要進一步處理的URL的 Request 對象盼理。
示例代碼:
import scrapy
class DmozSpider(scrapy.Spider):
? ? name = "dmoz"
? ? allowed_domains = ["dmoz.org"]
? ? start_urls = [
? ? ? ? "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
? ? ? ? "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
? ? ]
? ? def parse(self, response):
? ? ? ? filename = response.url.split("/")[-2]
? ? ? ? with open(filename, 'wb') as f:
? ? ? ? ? ? f.write(response.body)
Scrapy提供了一個 item pipeline 谈山,來下載屬于某個特定項目的圖片,比如宏怔,當(dāng)你抓取產(chǎn)品時奏路,也想把它們的圖片下載到本地。
這條管道臊诊,被稱作圖片管道鸽粉,在 ImagesPipeline 類中實現(xiàn),提供了一個方便并具有額外特性的方法抓艳,來下載并本地存儲圖片
使用圖片管道
示例代碼:
import scrapy
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.exceptions import DropItem
class MyImagesPipeline(ImagesPipeline):
? ? def get_media_requests(self, item, info):
? ? ? ? for image_url in item['image_urls']:
? ? ? ? ? ? yield scrapy.Request(image_url)
? ? def item_completed(self, results, item, info):
? ? ? ? image_paths = [x['path'] for ok, x in results if ok]
? ? ? ? if not image_paths:
? ? ? ? ? ? raise DropItem("Item contains no images")
? ? ? ? item['image_paths'] = image_paths
? ? ? ? return item
配置修改
開啟圖片管道
ITEM_PIPELINES = {'scrapy.contrib.pipeline.images.ImagesPipeline': 1}
指定路徑
IMAGES_STORE = '/path/to/valid/dir'
main文件編寫
當(dāng)我們使用scrapy編寫一個爬蟲工程后潜叛,想要對工程進行斷點調(diào)試,和內(nèi)部運行一般我們會定義一個main.py文件壶硅,
以運行jobbole為例威兜,編寫main.py 文件代碼。
from scrapy.cmdline import execute
import sys
import os
#設(shè)置工程目錄
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
#啟動命令
execute(['scrapy','crawl','jobbole'])
下載器中間件是介于Scrapy的request/response處理的鉤子框架庐椒。 是用于全局修改Scrapy request和response的一個輕量椒舵、底層的系統(tǒng)。
激活下載中間件
DOWNLOADER_MIDDLEWARES = {
? ? 'myproject.middlewares.CustomDownloaderMiddleware': 543,
}
爬蟲settings.py文件
# -*- coding: utf-8 -*-
# Scrapy settings for tutorial project
#
# For simplicitv, 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 = 'tutorial'#爬蟲項目的名稱
SPIDER_MODULES = ['tutorial.spiders']#爬蟲文件目錄
NEWSPIDER_MODULE = 'tutorial.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#用戶的代理约谈,設(shè)置用戶代理的目的是為了模擬瀏覽器發(fā)起請求
#USER_AGENT = 'tutorial (+http://www.yourdomain.com)'
# Obey robots.txt rules
#是否要遵守robot協(xié)議 默認(rèn)為true表示遵守 通常設(shè)置為false
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#下載器允許發(fā)起請求的最大并發(fā)數(shù)? 默認(rèn)情況下是16
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#下載延時 同一個網(wǎng)站上一個請求和下一個請求之間的間隔時間
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#在某一個域下? 允許的最大并發(fā)請求數(shù)量默認(rèn)8
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#對于單個ip下允許最大的并發(fā)請求數(shù)量 默認(rèn)為0 為零表示不限制
#特殊點:如果非零? 上面設(shè)置的針對于域的設(shè)置就會不再生效了
#這個時候并發(fā)的限制就會針對與ip而不會針對與網(wǎng)站
#特殊點:如果它非零? 我們下載延時不在是針對網(wǎng)站了 而是針對于ip了
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#針對于cookies設(shè)置一般情況下? 我們不攜帶cookies 也是反反爬的一個手段? 默認(rèn)為True
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#scrapy攜帶的一個終端擴展插件? telent作用:它能夠打印日志信息 監(jiān)聽爬蟲的爬取狀態(tài)信息
TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#默認(rèn)的請求頭? 他是一個全局的
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 = {
#? ? 'tutorial.middlewares.TutorialSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#下載中間件? 一般自定義下載中間件可以在這里激活? ? 后面的數(shù)字表示優(yōu)先級? 數(shù)字越小優(yōu)先級越高
#DOWNLOADER_MIDDLEWARES = {
#? ? 'tutorial.middlewares.TutorialDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#scrapy的擴展? 擴展信息
#EXTENSIONS = {
#? ? 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#在這里激活管道文件? ? 管道文件后面同樣跟了數(shù)字表示優(yōu)先級 數(shù)字越小表示優(yōu)先級越高
ITEM_PIPELINES = {
}
#寫入圖片的保存路徑
IMAGES_STORE = '/path/to/valid/dir'
#設(shè)置自動限速的擴展? 彌補上面的不足? 可以自動調(diào)整scrapy的下載時間? 時間延時
#
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.
# The initial download delay
# The maximum download delay to be set in case of high latencies
#在高延遲情況下最大的下載延遲(單位秒)
AUTOTHROTTLE_MAX_DELAY = 60
# each remote server
# Enable showing throttling stats for every response received:
#起用AutoThrottle調(diào)試(debug)模式笔宿,展示每個接收到的response±庥眨可以通過此來查看限速參數(shù)是如何實時被調(diào)整的泼橘。
AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#是否啟用緩存策略
HTTPCACHE_ENABLED = True
#緩存超時時間
HTTPCACHE_EXPIRATION_SECS = 0
#緩存保存路徑
HTTPCACHE_DIR = 'httpcache'
#緩存忽略的Http狀態(tài)碼
HTTPCACHE_IGNORE_HTTP_CODES = []
# 緩存存儲的插件
HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
Linux下scrapy框架命令使用
創(chuàng)建一個爬蟲項目:scrapy startproject 爬蟲的項目名稱
注意:創(chuàng)建爬蟲文件要在spiders文件下
創(chuàng)建爬蟲文件:scrapy genspider 爬蟲文件名稱 爬蟲的域
運行爬蟲的名稱:scrapy crawl 爬蟲文件名稱
創(chuàng)建crawlspider爬蟲文件:scrapy genspider –t crawl jobbole xxxxx.cn
未啟動爬蟲調(diào)試命令:scrapy shell 'http://www.xxxxxxx.cn/xxx/xxx'
scrapy框架安裝方式:
ubuntu系統(tǒng)下:sudo pip3 install scrapy
如果安裝不成功可嘗試安裝一下依賴環(huán)境
sudo apt-get install python3-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev