網路爬蟲-使用Scrapy爬取千圖網素材
阿新 • • 發佈:2018-12-16
話說好久好久好久沒寫過scrapy的demo了,已經快忘得差不多了,今天一個小老弟讓我幫他看看怎麼大量快速爬取千圖網的素材,我進網站看了看,一是沒有什麼反爬措施,二是沒有封ip的限制,那這種情況,鐵定用scrapy這個非同步框架最舒服了,於是花了十幾分鍾看了看自己以前寫的demo,哈哈,然後寫了個現成的~
千圖網這個其實呢很好寫,因為它圖片的地址是直接加載出來了的,並且沒有防盜鏈之類的騷操作,直接就可以下載到本地,只是分類的時候麻煩一點,我想的是定義一個全域性變數,從拼接Url的列表中分離出來,作為item的值,然後在pipelines裡面重寫ImagesPipeline的時候拿到這個分類名進行儲存
整個邏輯就是這樣的: ①從排程器拿到一個請求(該請求是通過拼接url字串得到的) ②解析該請求的原始碼,拿到圖片的src地址,並儲存在item ③通過pipelines管道,將解析後的response儲存在本地,即通過src的url下載圖片到本地,並進行分類 ④發現請求未完結,繼續從第一步開始
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from ..items import PicItem file_path = '' class PictureSpider(CrawlSpider): name = 'picture' allowed_domains = ['https://588cu.com'] def start_requests(self): base_url = 'http://588ku.com/sucai/0-default-0-0-{0}-0-{1}/' list1 = ["dongmanrenwu", "fengjingmanhua", "chuantongwenhua", "tiyuyundong", "huihuashufa", "beijingdiwen", "huabianhuawen", "biankuangxiangkuang", "ziranfengguang", "renwenjingguan", "jianzhuyuanlin", "yeshengdongwu", "jiaqinjiaxu", "yulei", "shenghuoyongpin", "canyinmeishi", "tiyuyongpin", "kexueyanjiu", "gongyeshengchan", "jiaotonggongju", "shangyechahua", "shangwuchangjing", "qita", "baozhuangsheji", "zhaotiesheji", "huacesheji"] for keyword in list1: # 拼接url global file_path file_path = keyword for page in range(1, 500): full_url = base_url.format(keyword, page) yield scrapy.Request(full_url, self.parse) def parse(self, response): pic_list = response.xpath('//*[@id="orgImgWrap"]/div') for i in pic_list: item = PicItem() item['src'] = i.xpath('div[1]/a/img/@data-original').extract_first() # 圖片地址 item['path'] = file_path # 圖片分類 yield item
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import logging import scrapy from scrapy.exceptions import DropItem from scrapy.pipelines.images import ImagesPipeline from scrapy.conf import settings logger = logging.getLogger('SaveImagePipeline') class SaveImagePipeline(ImagesPipeline): # 重構三個方法 def get_media_requests(self, item, info): logging.debug('圖片下載完成') yield scrapy.Request(url=item['src'], meta={'item':item}) def item_completed(self, results, item, info): if not results[0][0]: raise DropItem('下載失敗') return item def file_path(self, request, response=None, info=None): item = request.meta['item'] # 拆分檔名 file_name = request.url.split('/')[7].split('!')[0] final_path = u'{0}/{1}'.format(item['path'], file_name) return final_path
# -*- coding: utf-8 -*-
# Scrapy settings for pic 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 = 'pic'
SPIDER_MODULES = ['pic.spiders']
NEWSPIDER_MODULE = 'pic.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 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
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#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://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'pic.middlewares.PicSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'pic.middlewares.PicDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
IMAGES_STORE = './resources/'
ITEM_PIPELINES = {
'pic.pipelines.SaveImagePipeline': 300,
}
LOG_LEVEL = 'DEBUG'
# Enable and configure the AutoThrottle extension (disabled by default)
# 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
#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://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'
效果圖如下:
大功告成~! 需要原始碼的話可以去我的GitHub獲取(不定期更新各種小爬蟲)→→→傳送門