拥有了这个, 天下的美图都是你的!!!

简介: 拥有了这个, 天下的美图都是你的!!!

阅读本文只需要5分钟


美的东西就想要夺过来,占为己有, 本狗也不例外,哈哈哈哈哈!!!

今天本狗就给大家分享一串神奇的 ” 东东“, 它可以下载任意多的图片,因为本狗很喜欢那个网站的图片了, 所以就,,,, 而且都是高清图哦!!在此分享给大家!!!

语言:python     领域: 爬虫      框架: scrapy  (后续再详细议)

需要的模块:scrapy 以及python自带的模块    

安装命令: pip install scrapy

方案分析:

1 确定目标网站:”https://gratisography.com/page/1

2 使用正则表达式写好URL规则

3 然后根据xapth方法写提取信息(图片URL)

4 下载图片(scrapy框架自带异步下载)


上代码:

<1>主代码,主要获取图片URL

    import scrapy
    from scrapy.linkextractors import LinkExtractor
    from scrapy.spiders import CrawlSpider, Rule
    from images.items import ImagesItem
    class ImagesSpiderSpider(CrawlSpider):
        name = 'images_spider'
        allowed_domains = ['gratisography.com']
        start_urls = ['https://gratisography.com/page/1']
        rules = (
            Rule(LinkExtractor(allow=r'https://gratisography.com/page/\d'), follow=True),
            Rule(LinkExtractor(allow=r'https://gratisography.com/photo/+.?'), callback=
                 'parse_page', follow=False)
        )
        def parse_page(self, response):
           url_list = []
           title = response.xpath('//h1[@itemprop="name"]/text()').get()
           urls = response.xpath('//a[@class="buttons download-button"]/@href').get()
           url_list.append(urls)
           item = ImagesItem(title=title, image_urls=url_list)
           yield item

    <2>items,  存储URL代码

      import scrapy
      class ImagesItem(scrapy.Item):
          # define the fields for your item here like:
          title = scrapy.Field()
          image_urls = scrapy.Field()
          image = scrapy.Field()
      

      <3>middleware, 这次咱们用不着,再议

        from scrapy import signals
        class ImagesSpiderMiddleware(object):
            # Not all methods need to be defined. If a method is not defined,
            # scrapy acts as if the spider middleware does not modify the
            # passed objects.
            @classmethod
            def from_crawler(cls, crawler):
                # This method is used by Scrapy to create your spiders.
                s = cls()
                crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
                return s
            def process_spider_input(self, response, spider):
                # Called for each response that goes through the spider
                # middleware and into the spider.
                # Should return None or raise an exception.
                return None
            def process_spider_output(self, response, result, spider):
                # Called with the results returned from the Spider, after
                # it has processed the response.
                # Must return an iterable of Request, dict or Item objects.
                for i in result:
                    yield i
            def process_spider_exception(self, response, exception, spider):
                # Called when a spider or process_spider_input() method
                # (from other spider middleware) raises an exception.
                # Should return either None or an iterable of Response, dict
                # or Item objects.
                pass
            def process_start_requests(self, start_requests, spider):
                # Called with the start requests of the spider, and works
                # similarly to the process_spider_output() method, except
                # that it doesn鈥檛 have a response associated.
                # Must return only requests (not items).
                for r in start_requests:
                    yield r
            def spider_opened(self, spider):
                spider.logger.info('Spider opened: %s' % spider.name)
        class ImagesDownloaderMiddleware(object):
            # Not all methods need to be defined. If a method is not defined,
            # scrapy acts as if the downloader middleware does not modify the
            # passed objects.
            @classmethod
            def from_crawler(cls, crawler):
                # This method is used by Scrapy to create your spiders.
                s = cls()
                crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
                return s
            def process_request(self, request, spider):
                # Called for each request that goes through the downloader
                # middleware.
                # Must either:
                # - return None: continue processing this request
                # - or return a Response object
                # - or return a Request object
                # - or raise IgnoreRequest: process_exception() methods of
                #   installed downloader middleware will be called
                return None
            def process_response(self, request, response, spider):
                # Called with the response returned from the downloader.
                # Must either;
                # - return a Response object
                # - return a Request object
                # - or raise IgnoreRequest
                return response
            def process_exception(self, request, exception, spider):
                # Called when a download handler or a process_request()
                # (from other downloader middleware) raises an exception.
                # Must either:
                # - return None: continue processing this exception
                # - return a Response object: stops process_exception() chain
                # - return a Request object: stops process_exception() chain
                pass
            def spider_opened(self, spider):
                spider.logger.info('Spider opened: %s' % spider.name)
        

        <4>pipelines, 通过URL再管道下载图片

          import os
          from queue import Queue
          from urllib import request
          import threading
          class ImagesPipeline(object):
              def __init__(self):
                  self.path = os.path.join(os.path.dirname(os.path.dirname(__file__) ),'photo')
                  if not os.path.exists(self.path):
                      os.mkdir(self.path)
              def process_item(self, item, spider):
                  title = item.get('title')
                  urls = item.get('image_urls')
                  for url in urls:
                      image_name = url.split('-')[-1]
                      request.urlretrieve(url, os.path.join(self.path, image_name))
                  return item
          

          <5>settings, 一些基础设置, 比如要开启管道, 基础防爬特征等

            import os
            BOT_NAME = 'images'
            SPIDER_MODULES = ['images.spiders']
            NEWSPIDER_MODULE = 'images.spiders'
            # Crawl responsibly by identifying yourself (and your website) on the user-agent
            #USER_AGENT = 'images (+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://doc.scrapy.org/en/latest/topics/settings.html#download-delay
            # See also autothrottle settings and docs
            DOWNLOAD_DELAY = 1
            # 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 6.1; Win64; x64) AppleWebKit/537.36 '
                            '(KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36'
            }
            # Enable or disable spider middlewares
            # See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
            #SPIDER_MIDDLEWARES = {
            #    'images.middlewares.ImagesSpiderMiddleware': 543,
            #}
            # Enable or disable downloader middlewares
            # See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
            #DOWNLOADER_MIDDLEWARES = {
            #    'images.middlewares.ImagesDownloaderMiddleware': 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
            ITEM_PIPELINES = {
               # 'images.pipelines.ImagesPipeline': 300,
              'scrapy.pipelines.images.ImagesPipeline': 1 
            }
            # 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'
            # 下载图片路径设置
            IMAGES_STORE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'photo')

            <6>start, 自己写的,只要运行这个,整个框架就开始工作了。 告别黑屏时代(cmd)


            from scrapy import cmdline
            cmdline.execute('scrapy crawl images_spider'.split())

            下期带上效果图哦  2019-5-14 测试正常  若失效,联系ME!!

            套路都一样!!!就喜欢这句话!!! 回复【美图】获取源码

            相关文章
            |
            SQL 关系型数据库 数据库
            RDS入门——Excel文件转存到RDS数据库实践
            本实验将帮助您快速掌握RDS产品的实例开通,熟悉RDS产品的常用功能与基础操作,完成云上数据库搭建。
            |
            11月前
            |
            存储 自然语言处理 BI
            从 Elasticsearch 到 Apache Doris 腾讯音乐内容库升级,统一搜索分析引擎,成本直降 80%
            实现写入性能提升 4 倍、使用成本节省达 80% 的显著成效
            379 1
            从 Elasticsearch 到 Apache Doris 腾讯音乐内容库升级,统一搜索分析引擎,成本直降 80%
            【PCB设计秘籍】AutoDesk Eagle轻松驾驭:LMC555CN/NOPB器件库下载与添加全攻略,设计效率飙升!
            【8月更文挑战第2天】【PCB设计】AutoDesk Eagle如何下载和添加LMC555CN或LMC555CN/NOPB器件的库
            349 11
            |
            算法 前端开发 NoSQL
            追忆四年前:一段关于我被外企CTO用登录注册吊打的不堪往事
            是的,诸位没有看错,这篇文章的要讲述的并不是我吊打面试官,而是一段我被面试官吊打的陈年往事,这段痛苦的记忆在我脑海中长久不衰,也是一个我内心曾多次不愿面对的事实,各位看官可以准备好一小把瓜子,听我将这则旧事缓缓道来~
            491 59
            追忆四年前:一段关于我被外企CTO用登录注册吊打的不堪往事
            |
            11月前
            |
            存储 SQL 关系型数据库
            【入门级教程】MySQL:从零开始的数据库之旅
            本教程面向零基础用户,采用通俗易懂的语言和丰富的示例,帮助你快速掌握MySQL的基础知识和操作技巧。内容涵盖SQL语言基础(SELECT、INSERT、UPDATE、DELETE等常用语句)、使用索引提高查询效率、存储过程等。适合学生、开发者及数据库爱好者。
            364 0
            【入门级教程】MySQL:从零开始的数据库之旅
            |
            10月前
            |
            关系型数据库 分布式数据库 数据库
            锦鲤附体 | PolarDB数据库创新设计赛,好礼不停!
            锦鲤附体 | PolarDB数据库创新设计赛,好礼不停!
            |
            11月前
            |
            NoSQL 数据管理 关系型数据库
            利用阿里云的尖端数据库解决方案增强游戏数据管理
            利用阿里云的尖端数据库解决方案增强游戏数据管理
            |
            11月前
            |
            存储 小程序 Apache
            10月26日@杭州,飞轮科技 x 阿里云举办 Apache Doris Meetup,探索保险、游戏、制造及电信领域数据仓库建设实践
            10月26日,由飞轮科技与阿里云联手发起的 Apache Doris 杭州站 Meetup 即将开启!
            209 0
            |
            存储 运维 Cloud Native
            "Flink+Paimon:阿里云大数据云原生运维数仓的创新实践,引领实时数据处理新纪元"
            【8月更文挑战第2天】Flink+Paimon在阿里云大数据云原生运维数仓的实践
            441 3
            |
            存储 数据采集 分布式计算
            阿里巴巴数据仓库实践:从离线到实时的一体化探索
            阿里巴巴的数据仓库实践从离线到实时的一体化探索,不仅为企业自身业务的快速发展提供了有力支撑,也为行业树立了标杆。通过不断优化技术架构、提升数据处理能力、加强数据治理和安全管理,阿里巴巴的实时数仓将为企业创造更大的价值,推动数字化转型的深入发展。未来,随着技术的不断进步和业务的持续拓展,阿里巴巴的实时数仓实践将展现出更加广阔的应用前景和发展空间。