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

2020-02-13 14:05:37 浏览数 (1)

阅读本文只需要5分钟

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

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

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

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

安装命令: pip install scrapy

方案分析:

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

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

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

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

上代码:

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

代码语言:javascript复制
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代码

代码语言:javascript复制
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, 这次咱们用不着,再议

代码语言:javascript复制
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再管道下载图片

代码语言:javascript复制
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, 一些基础设置, 比如要开启管道, 基础防爬特征等

代码语言:javascript复制
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)

代码语言:javascript复制
from scrapy import cmdline
cmdline.execute('scrapy crawl images_spider'.split())

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

套路都一样!!!就喜欢这句话!!! 回复【美图】获取源对我最大的热爱就是关注我,蟹蟹!!!

0 人点赞