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
……

 

您好!对于使用Scrapy爬取图片并保存的问题,您可以按照以下步骤进行操作: 1. 首先,确保您已经安装了Scrapy库。如果没有安装,可以通过以下命令进行安装: ``` pip install scrapy ``` 2. 创建一个新的Scrapy项目。在命令行使用以下命令: ``` scrapy startproject project_name ``` 这将在当前目录下创建一个名为 "project_name" 的新项目文件夹。 3. 进入项目文件夹,并创建一个新的Spider。在命令行使用以下命令: ``` cd project_name scrapy genspider spider_name example.com ``` 这将在项目创建一个名为 "spider_name" 的新Spider,用于定义爬取网页的规则。 4. 打开生成的Spider代码文件(位于 "project_name/spiders/spider_name.py"),并添加以下代码: ```python import scrapy class MySpider(scrapy.Spider): name = 'spider_name' start_urls = ['http://www.example.com'] # 要爬取的起始URL def parse(self, response): # 在这里编写解析响应数据的代码 # 提取图片URL并发送请求进行下载 for img_url in response.css('img::attr(src)').getall(): yield scrapy.Request(url=response.urljoin(img_url), callback=self.save_image) def save_image(self, response): # 获取图片保存路径 image_path = 'path/to/save/image.jpg' # 根据需求自定义保存路径和文件名 # 保存图片 with open(image_path, 'wb') as f: f.write(response.body) ``` 在上述代码,我们定义了一个Spider类,包含了起始URL和解析响应数据的方法。在parse方法,我们使用CSS选择器提取图片的URL,并使用scrapy.Request发送请求进行下载。下载后的图片会通过save_image方法保存到本地。 5. 运行爬虫。在命令行使用以下命令: ``` scrapy crawl spider_name ``` 这将启动爬虫并开始爬取网页上的图片。下载的图片将保存在您指定的路径下。 请注意,上述代码只是一个简单示例,您可能需要根据具体的网页结构和需求进行相应的修改。另外,确保您遵守网站的爬取规则并尊重版权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值