美文网首页爬遍全网
摄图网海量图片爬取

摄图网海量图片爬取

作者: 可爱多多少 | 来源:发表于2021-09-27 08:22 被阅读0次

    1.引言

    爬取摄图网插画栏目中各个类目下的全部图片。

    要求:将所有爬取的图片保存至以各自所属类别命名的文件夹中。

    2.流程分析

    首先这个任务属于一个两层网络爬虫,因为实际图片的下载路径位于第二层,所以我们必须从第一层网页中获取第二层网页的URL,接着从第二层网页中抓取各个图片的下载地址。


    在这里插入图片描述

    上图展示的网页是我们初始请求的网页,其中每个图片对应一个插画类目,共100多个类目;我们需要请求该网页,并抓取每个插画类目对应的URL。


    在这里插入图片描述
    由上图CSS选择器定位情况,我们知道一共有120个插画类目,每一个类目都存储在<div class="pl-list>标签中;相应的,每个类目的URL也存储在其中。
    在这里插入图片描述

    进入到其中的开学季插画类目,利用CSS选择器定位到每张图片的下载地址,我们发现一共有100张图片。

    根据以上的分析,我们的目标是爬取并下载120个插画类目下共12000张图片。

    3.代码实现

    • 新建项目

    在终端分别输入以下命令行,新建爬虫项目。

    scrapy startproject shetuwang
    
    cd shetu
    scrapy genspider picture 699pic.com 
    
    • 编写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 ShetuwangItem(scrapy.Item):
        title = scrapy.Field() #图片所属类别
        imgurls = scrapy.Field() #图片下载地址
        images = scrapy.Field() #图片信息
        
        # define the fields for your item here like:
        # name = scrapy.Field()
        #pass
    
    
    • 编写picture.py源文件,制定爬虫的数据爬取工作
    import scrapy
    from scrapy import Request
    from ..items import ShetuwangItem
    
    class PictureSpider(scrapy.Spider):
        name = 'picture'
        allowed_domains = ['699pic.com']
        start_urls = ['http://699pic.com/chahua/']
    
        def parse(self, response):
            typeurls = response.css(".pl-list a::attr(href)").extract()
            for imgurl in typeurls:
                imgurl = 'https:'+imgurl
                yield Request(imgurl,callback=self.parse_image)
                
        def parse_image(self,response):
            item = ShetuwangItem()
            
            imageurls = response.css("div.list a img::attr(data-original)").extract()
            if imageurls:
                title = response.css("strong.Gjc::text").extract()[0]
                item['title'] = title
                
            imgurls = []
            for imageurl in imageurls:
                imageurl = 'https:' + imageurl
                imgurls.append(imageurl)
                
            item['imgurls'] = imgurls
            yield item
    
    • 编写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
    from scrapy.pipelines.images import ImagesPipeline
    from scrapy import Request
    
    class ShetuwangPipeline:
        def process_item(self, item, spider):
            return item
    
    class DownloadImagesPipeline(ImagesPipeline):
        def get_media_requests(self,item,info):
            for imgurl in item['imgurls']:
                yield Request(imgurl,meta={'title':item['title']})
                
        def file_path(self,request,response=None,info=None):
            title = request.meta['title']
            imgname = request.url.split('/')[-1]
            filename = u'{0}/{1}'.format(title,imgname)
            return filename
        
        def thumb_path(self,request,thumb_id,response=None,info=None):
            title = request.meta["title"]
            image_name = request.url.split("/")[-1]
            thumbname = u'{0}/{1}/{2}'.format(title,thumb_id,image_name)
            return thumbname
    
    • 编写settings.py源文件,配置爬虫项目
    # Scrapy settings for shetuwang 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 = 'shetuwang'
    
    SPIDER_MODULES = ['shetuwang.spiders']
    NEWSPIDER_MODULE = 'shetuwang.spiders'
    
    
    # Crawl responsibly by identifying yourself (and your website) on the user-agent
    #USER_AGENT = 'shetuwang (+http://www.yourdomain.com)'
    
    # 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://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',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67',
    }
    
    # Enable or disable spider middlewares
    # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
    #SPIDER_MIDDLEWARES = {
    #    'shetuwang.middlewares.ShetuwangSpiderMiddleware': 543,
    #}
    
    # Enable or disable downloader middlewares
    # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
    #DOWNLOADER_MIDDLEWARES = {
    #    'shetuwang.middlewares.ShetuwangDownloaderMiddleware': 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 = {
       #'shetuwang.pipelines.ShetuwangPipeline': 300,
        'shetuwang.pipelines.DownloadImagesPipeline': 300,
    }
    
    IMAGES_STORE = 'D:\\scrapy\\shetuwang'
    IMAGES_URLS_FIELD = 'image_urls'
    IMAGES_RESULT_FIELD = 'images'
    IMAGES_THUMBS = {'small':(80,80),'big':(300,300)}
    
    
    # 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'
    
    • 在终端用命令行运行爬虫,进行爬取
    scrapy crawl picture
    
    • 查看运行结果

    在没有分布式爬取技术加持的情况下,12000张图片爬取下来需要较长时间,这里只展示爬取到的部分图片。


    在这里插入图片描述

    此刻只爬取完了两个类目,分别是开学季插画、微光渐变插画。


    开学季
    以上为开学季插画,还包含两个不同尺寸的缩略图。
    微光渐变

    以上为微光渐变插画,及不同尺寸的缩略图。

    3.更深入

    通过查看下载的图片,我发现每张图片上都有水印;需要有摄图网账号,且注册会员才能下载无水印图片。

    如果我已经满足了下载无水印图片的资质了,该如何改进这个项目,进行无水印图片的爬取呢?

    欢迎大家来评论区交流意见!

    写在最后

    全套爬虫开发环境配置

    人类之奴

    相关文章

      网友评论

        本文标题:摄图网海量图片爬取

        本文链接:https://www.haomeiwen.com/subject/yclhnltx.html