【爬虫】scrapy图片爬取imagesPipeline

爬取字符串和爬取图片的区别

  • 字符串:基于xpath进行解析提价管道进行持久化存储
  • 图片:xpath解析出图片src属性,对图片地址发起请求获取图片二进制类型数据

ImagesPipeline

将img的src属性进行解析,提交到管道,管道会对src进行请求发送获取图片的二进制类型的数据且进行持久化存储

使用流程

  1. 数据解析。解析出图片地址。
  2. 将存储图片地址的item提交到imagespipeline管道类
  3. 在管道文件中自定义一个基于ImagesPipeline的管道类(重写三个方法)
  4. 配置文件中指定存储目录,指定开启管道

爬虫文件

import scrapy
# 爬取站长素材中的高清图片

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

    def parse(self, response):
        div_list = response.xpath('//*[@id="container"]/div')
        for div in div_list:
            img_src = div.xpath('./div/a/img/@src').extract_first()
            print(img_src)


获取到的src均为空
在这里插入图片描述
在这里插入图片描述
随着滚动条下滑,图片出现在可视化界面中,src2动态变为src。由于scrapy发起请求没有可视化界面,均为伪属性src2,所以返回的均为none。因此修改源代码为src2即可。

import scrapy
from spider.imgsPro.imgsPro.items import ImgsproItem
# 爬取站长素材中的高清图片

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

    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中
            item = ImgsproItem()
            item['img_src'] = img_src
            # 提交item到管道
            yield item

输出如下,获取到了src
在这里插入图片描述
item文件

import scrapy


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

管道文件

from scrapy.pipelines.images import ImagesPipeline
import scrapy

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

    # 进行持久化存储的路径
    def file_path(self, request, response=None, info=None):
        # 指定图片名称。图片存储目录在配置文件中设置
        img_name = request.url.split('/')[-1]
        return img_name

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

配置文件

BOT_NAME = 'imgsPro'

SPIDER_MODULES = ['imgsPro.spiders']
NEWSPIDER_MODULE = 'imgsPro.spiders'

LOG_LEVEL = 'ERROR'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows 。。。。。。。。。。。。。。。。。。。'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
   'imgsPro.pipelines.ImgsproPipeline': 300,
}
# 指定图片存储目录
IMAGES_STORE = './imgsW'

爬取结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值