python学习

Python学习八十四天:图片下载

2019-05-14  本文已影响6人  暖A暖

今天要学习的是图片下载,Scrapy用ImagesPipeline类提供一种方便的方式来下载和存储图片;

import scrapy
class XkdDribbbleSpiderItem(scrapy.Item):
    title = scrapy.Field()
    image_url = scrapy.Field()
    date = scrapy.Field()
from .pipelines import ImagePipeline
import os

# 获取项目根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

ITEM_PIPELINES = {
   # 'XKD_Dribbble_Spider.pipelines.XkdDribbbleSpiderPipeline': 300,
   # 当items.py模块yield之后,默认就是下载image_url的页面
   'scrapy.pipelines.images.ImagePipeline': 1,
}

# 获取item中,image_url的地址,并且下载
IMAGES_URLS_FIELD = 'image_url'

# 指定图片下载存储的路径
IMAGES_STORE = os.path.join(BASE_DIR, 'images')
import scrapy
from urllib import parse
from scrapy.http import Request
from ..items import XkdDribbbleSpiderItem
from datetime import datetime

class DribbbleSpider(scrapy.Spider):
    name = 'dribbble'
    allowed_domains = ['dribbble.com']
    start_urls = ['https://dribbble.com/stories']

    def parse(self, response):
        # 获取a标签的url值
        # urls = response.css('h2 a::attr(href)').extract()
        a_nodes = response.css('header div.teaser a')
        for a_node in a_nodes:
            # print(a_node)
            a_url = a_node.css('::attr(href)').extract()[0]
            a_image_url = a_node.css('img::attr(src)').extract()[0]
            yield Request(url=parse.urljoin(response.url, a_url), callback=self.parse_analyse, meta={'a_image_url': a_image_url})

    def parse_analyse(self, response):
        a_image_url = response.meta.get('a_image_url')
        title = response.css('.post header h1::text').extract()[0]
        date = response.css('span.date::text').extract_first()
        date = date.strip()
        date = datetime.strptime(date, '%b %d, %Y').date()

        # 构建模型
        dri_item = XkdDribbbleSpiderItem()
        dri_item['a_image_url'] = a_image_url
        dri_item['title'] = title
        dri_item['date'] = date
        yield dri_item
# 导入自定义ImagePipeline需要的库
from scrapy.http import Request
from scrapy.utils.python import to_bytes
import hashlib
from scrapy.pipelines.images import ImagesPipeline
from datetime import datetime
class XkdDribbbleSpiderPipeline(object):
    def process_item(self, item, spider):
        return item
class ImagePipeline(ImagesPipeline):
    def file_path(self, request, response=None, info=None):
        ## start of deprecation warning block (can be removed in the future)
        def _warn():
            from scrapy.exceptions import ScrapyDeprecationWarning
            import warnings
            warnings.warn('ImagesPipeline.image_key(url) and file_key(url) methods are deprecated, '
                          'please use file_path(request, response=None, info=None) instead',
                          category=ScrapyDeprecationWarning, stacklevel=1)
        # check if called from image_key or file_key with url as first argument
        if not isinstance(request, Request):
            _warn()
            url = request
        else:
            url = request.url
        # detect if file_key() or image_key() methods have been overridden
        if not hasattr(self.file_key, '_base'):
            _warn()
            return self.file_key(url)
        elif not hasattr(self.image_key, '_base'):
            _warn()
            return self.image_key(url)
        ## end of deprecation warning block
        image_guid = hashlib.sha1(to_bytes(url)).hexdigest()  # change to request.url after deprecation
        # 修改为时间为目录
        return '{}/{}.jpg'.format(datetime.now().year,image_guid)

运行代码我们能看到打印出来的信息,显示的字段信息是根据我们在蜘蛛文件中构建的模型决定的。然后这些图片就会下载到我们指定的文件夹中


Pipeline介绍

参考:https://www.9xkd.com/user/plan-view.html?id=1835482827

上一篇 下一篇

猜你喜欢

热点阅读