话说好久好久好久没写过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获取(不定期更新各种小爬虫)→→→传送门