17. python爬虫——基于scrapy框架中的ImagesPipline进行图片数据爬取

基于scrapy框架中的ImagesPipline进行图片数据爬取

1、介绍

基于scrapy爬取字符串类型的数据和爬取图片类型的数据区别?

  • 字符串:只需要基于xpath进行解析且提交管道进行持久化存储。
  • 图片:xpath解析出图片src的属性值,单独的对图片地址发起请求获取图片二进制类型的数据。

ImagesPipeline:

只需要将img的src的属性值进行解析,提交到管道,管道就会对图片的src的属性值进行请求发送,并且获取图片的二进制类型的数据且还可以实现持久化存储。

2、需求

爬取http://sc.chinaz.com/tupian/的高清图片

使用流程:

  1. 数据解析:解析出图片的地址
  2. 将存储图片地址的item提交到指定的管道类
  3. 在管道文件中自定制一个基于ImagesPipLine的一个管道类,重写以下三个方法:
    - get_media_requests(self, item, info)
    - file_path(self, request, response=None, info=None)
    - item_completed(self, results, item, info)
  4. 在配置文件中
    - 指定图片存储的目录:IMAGES_STORE = ‘./img_Path’
    - 指定开启的管道:自定制的管道类ITEM_PIPELINES

创建工程:scrapy startproject imgsPro
进入imgsPro创建spiders:scrapy genspider img www.xxx.com

3、分析

打开抓包工具,发现图片在img的src属性中
在这里插入图片描述
但下方的img标签中还有src2属性
在这里插入图片描述

知识点:
src是可视化界面可实际展示的,src2是伪属性,用于滑动滚轮时动态加载图片。由于我们在爬取该网站时,并没有可视化界面展示,因此解析数据时使用的是src2伪属性来获取图片地址。

4、代码编写及实现效果

settings.py

USER_AGENT = 'Mozilla/...
ROBOTSTXT_OBEY = False
ITEM_PIPELINES = {
#   'imgsPro.pipelines.ImgsproPipeline': 300,
    'imgsPro.pipelines.imgsPipleLine': 300,
}
IMAGES_STORE = './imgs_biubiu'

img.py

import scrapy
from imgsPro.items import ImgsproItem

class ImgSpider(scrapy.Spider):
    name = 'img'
    allowed_domains = ['www.xxx.com']
    start_urls = ['http://sc.chinaz.com/tupian/']

    def parse(self, response):
        div_list = response.xpath('//*[@id="container"]/div')
        for div in div_list:
            #注意:解析时需适用伪属性
            img_src = div.xpath('./div/a/img/@src2').extract_first()
            print(img_src)

            item = ImgsproItem()
            item['img_src'] = img_src

            yield item

items.py

import scrapy


class ImgsproItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    img_src = scrapy.Field()

piplines.py中需要重写ImagesPipeline的类

from scrapy.pipelines.images import ImagesPipeline
import scrapy

class imgsPipleLine(ImagesPipeline):

    #可以根据图片地址进行图片数据的请求
    def get_media_requests(self, item, info):
        yield scrapy.Request(item['img_src'])

    def file_path(self, request, response=None, info=None):
        imgName = request.url.split('/')[-1]
        return imgName

    def item_completed(self, results, item, info):
        #返回给下一个即将被执行的管道类
        return item

执行scrapy crawl img完成爬取
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰阳星宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值