scrapy下载大文件
大文件下载
大文件下载,需要将请求到的数据在管道中进行下载;
依赖:
Pillow模块 安装:pip install Pillow 若安装失败,使用下载地址,下载到本地安装:https://www.lfd.uci.edu/~gohlke/pythonlibs/#_pillow
实例:
需求:将摄图网第一页图片已标题为名称下载到本地保存.jpg格式;
spiders-->img.py
import re import scrapy from imgPro.items import ImgproItem class ImgSpider(scrapy.Spider): name = 'img' # allowed_domains = ['www.xxx.com'] start_urls = ['http://699pic.com/image/1'] def parse(self, response): # 解析图片地址和图片名称//*[@id="pins"]/li[1] li_list = response.xpath('//div[@class="special-list clearfix"]/div') for li in li_list: category = li.xpath("./a[@class='special-list-title']/h2/text()").extract_first() + ".jpg" url = li.xpath("./div/a/img/@src").extract_first() pattern = re.compile("//(.*?)!.*$") # 定义规则 rule_list = pattern.findall(url) # print("是什么到了这里了啊",rule_list) item = ImgproItem() for i in range(len(rule_list)): item["image_url"] = "https://{0}".format(rule_list[i]) item["images_name"] = category yield item
items.py
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class ImgproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() images_name = scrapy.Field() image_url = scrapy.Field()
settings.py
# Scrapy settings for imgPro 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 = 'imgPro' SPIDER_MODULES = ['imgPro.spiders'] NEWSPIDER_MODULE = 'imgPro.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'imgPro (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False LOG_LEVEL = "ERROR" # 定义只输出错误的日志 USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36' IMAGES_STORE = "./imgLibs66" # 存储图片的文件夹,存在就直接存储,不存在spider自动创建该文件夹 # 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://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: #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://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'imgPro.middlewares.ImgproSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'imgPro.middlewares.ImgproDownloaderMiddleware': 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 = { 'imgPro.pipelines.MyImagesPipeline': 1, 'imgPro.pipelines.ImgproPipeline': 2, } # 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'
pipelines.py
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter # 管道需要接收item中的图片地址和名称,然后管道中请求到图片的数据对其进行持久化存储 import scrapy # 该默认管道无法帮助我们请求图片数据,因此该管道就不用了 class ImgproPipeline: def process_item(self, item, spider): return item from scrapy.pipelines.images import ImagesPipeline # 提供数据下载功能 class MyImagesPipeline(ImagesPipeline): """重写父类的三个方法,需要在配置文件中配置""" # 发送请求,根据图片地址发起请求 def get_media_requests(self, item, info): # 这个方法是在发送下载请求之前调用的,其实这个方法本身就是去发送下载请求的 yield scrapy.Request(url=item['image_url'], meta={"item": item}) # 指定图片存储地址 def file_path(self, request, response=None, info=None, *, item=None): # 通过request获取meta item = request.meta["item"] filePath = item["images_name"] return filePath # 只需要返回图片名称,图片存储需要在settings中添加配置:IMAGES_STORE = "./imgLibs" # 将item传递给下一个即将被执行的管道类 def item_completed(self, results, item, info): return item
总结:下载管道类是scrapy封装好的直接使用即可:
from scrapy.pipelines.images import ImagesPipeline 重写该管道类的三个方法: get_media_requests 对图片地址发起请求 file_path 返回图片名称即可 item_completed 返回item,将其返回给下一个即将被执行的管道类 在配置文件中添加: IMAGES_STORE = "/dirName"