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

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

阅读本文只需要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!!

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

            相关文章
            |
            安全 芯片
            小小汉瓦如何变身科技范儿?
            汉能汉瓦即将进入“高产期”。 4月15日,汉能汉瓦系列新品发布会在北京奥森公园的汉能总部举行。这是继去年7月发布双玻系列汉瓦后,汉能在9个月后,再次推出升级版产品。
            190 0
            小小汉瓦如何变身科技范儿?
            |
            人工智能 物联网 5G
            搭上“阿里号”快车 联发科技华丽转身
            美国当地时间1月9日,在2018国际消费电子展(CES)上,台湾芯片巨头联发科技(2454.TW)与阿里巴巴人工智能实验室(AI labs)签署了战略合作协议,针对智能家居控制协议、物联网芯片定制、AI智能硬件等领域展开长期密切合作,助力加速智能物联网(IoT)发展。
            281 0
            搭上“阿里号”快车 联发科技华丽转身
            |
            新零售 运维 自然语言处理
            微盟与汇付天下的“1+1>2”
            微盟与汇付天下的“1+1>2”
            147 0
            微盟与汇付天下的“1+1>2”
            百度之星之D:共同狂欢
            百度2005年8月5日上市时,在北京和纳斯达克的同学们每一个小时整点时就会通一次电话,对一下表,确认一切相关活动都精确同步。但是要注意,在两边的同学位于不同的时区,在夏时制时,两地时差12小时,因此,每次对表都需要做一下时区转换。你来帮我们完成这个有点麻烦的工作吧。
            159 0
            百度之星之D:共同狂欢
            |
            运维 Cloud Native 架构师
            282天,汇付天下“冲上云霄”
            这家支付巨头用282天的时间,创造了“云原生”变革的行业奇迹。
            6326 0
            282天,汇付天下“冲上云霄”
            |
            新零售 供应链 双11
            比肩雪梨张大奕,网红于momo身边有个秘密武器
            10月25日,刚忙完淘宝店店庆的于MOMO抽空飞到深圳。她不是来拍照,也不是来工厂看订单,而是参加福布斯中国举办的活动。作为优秀创业者,她入选了2017福布斯中国30位30岁以下精英榜。 在各自不同的领域,这些上榜的年轻人们正在用自己的力量改变世界。
            2711 0