Scrapy保存图片&自定义保存

一、爬取昵图网

第一步:

1、新建项目

scrapy startproject nituwang

2、新建爬虫

scrapy genspider nituwang_spider nipic.com

3、更改设置

……

第二步:

1、爬虫启动文件

from scrapy import cmdline

cmdline.execute("scrapy crawl  --nolog nituwang_spider".split()) #启动爬虫,无日志

 第三步:

1、写items.py文件:

       用来存放爬虫爬取下来数据的模型,类似Django的models,不过这个没有整型、字符……之分。

 items.py

import scrapy


class NituwangItem(scrapy.Item):
    big_image_url = scrapy.Field() #存放高清大图
    title = scrapy.Field()        #图的名字

第四步:

1、写爬虫:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from urllib import parse
import re
from ..items import NituwangItem


class NituwangSpiderSpider(scrapy.Spider):
    name = 'nituwang_spider'
    allowed_domains = ['nipic.com']
    start_urls = ['http://www.nipic.com/photo/lvyou/ziran/index.html', ]  # 爬虫开始url

    def parse(self, response):
        image_urls = response.xpath('//li[contains(@class,"new-works-box")]/a/@href').getall()
        # 图片详情页
        for image_url in image_urls:
            # 发起请求,->图片详情页,解析图片详情页。
            yield Request(parse.urljoin(response.url, image_url), callback=self.parse_detail)

        # 获取总页数。因为这个网址的最后一页的下一页是第一页
        end_link = response.xpath('//a[@class="bg-png24 page-btn"][2]/@href').get()
        res = re.match('.*?(\d{1,10})', end_link)
        end_num = res.group(1)
        for i in range(1, int(end_num)):
            url = 'http://www.nipic.com/photo/lvyou/ziran/index.html?page={}'.format(i)
            # 请求下一页,继续解析
            yield Request(url, callback=self.parse)

    # 图片详情页,获取高清大图
    def parse_detail(self, response):
        item = NituwangItem()
        big_image_url = response.xpath('//img[@id="J_worksImg"]/@src').get()  # 大图链接
        item['big_image_url'] = [big_image_url]  # 传递列表,下载图片需要使用列表
        item['title'] = response.xpath('//img[@id="J_worksImg"]/@alt').get() #图片名
        return item

 第五步:

1、进入pipelines,对爬取下来的数据进行操作。

get_media_requests----->file_path--->item_completed
from scrapy.pipelines.images import ImagesPipeline
from scrapy.http import Request
import random


class MyImagePipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        '''
        是在发送下载请求之前调用
        去发送下载图片的请求
        '''
        #meta用来传递信息,在file_path中没有item信息。
        for image_url in item['big_image_url']:
            yield Request(image_url, meta={'title': item['title']})

    def item_completed(self, results, item, info):
        print('******the results is********:', results) #也可以在这个方法中更改文件名,因为在file_path存储完成后,item_completed里有个results参数,results参数保存了图片下载的相关信息
        return item

    def file_path(self, request, response=None, info=None):
        '''
        这个方法是在图片将要被存储的时候调用,来获取这个图片存储的路径
        :param request:
        :param response:
        :param info:
        :return: 存储路径
        '''
        a = 'abcdefghijklmnopqrstuvwxyz1234567890'
        b = ''.join(random.sample(a, 10))
        title = request.meta['title'].strip() + b  # 因为会有重复的名字,所以从随机提取几个字符
        path = '风景/%s.jpg' % (title)
        return path

第六步:

1、在settings.py文件中设置

……
ITEM_PIPELINES = {
    # 'nituwang.pipelines.NituwangPipeline': 300,
    # 'scrapy.pipelines.images.ImagesPipeline': 1,
    'nituwang.pipelines.MyImagePipeline': 1,

}
path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(path, 'images')
IMAGES_STORE = path  # 存储的路径,不写绝对路径,在别的系统运行时,需要重新设定。
IMAGES_URLS_FIELD = 'big_image_url'  # 要下载的字段,使用哪个url
……

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值