基于scrapy爬取字符串类型的数据和爬取图片类型的数据区别?
1.字符串:只需要基于xpath进行解析且提交管道进行持久化存储
2.图片:xpath解析出图片src的属性值。需要单独对图片地址发起请求获取图片二进制类型的数据
ImagesPipeline
只需要将img的src的属性值进行解析,然后提交给管道,管道就会对图片的src进行请求发送获取图片的二进制数据,同时进行持久化存储。
需求:爬取站长素材中的高清图片
步骤1:数据解析
import scrapy
from imgPro.items import ImgproItem
class ImgesSpider(scrapy.Spider):
name = 'imges'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://699pic.com/lifestyle.html']
#数据解析
def parse(self, response):
div_list = response.xpath('//*[@id="wrapper"]/div[3]/div/div')
item = ImgproItem()
for div in div_list:
url = 'https:' + div.xpath('./a/img/@data-original-srcset').extract_first()
src = url.split(' ')[0]
item['src'] = src
yield item
步骤2.item.py
src = scrapy.Field()
步骤3.pipelines.py【图片解析URL,并完成持久化存储】
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
import scrapy
from itemadapter import ItemAdapter
# class ImgproPipeline:
# def process_item(self, item, spider):
# print(item)
# return item
from scrapy.pipelines.images import ImagesPipeline
import scrapy
#重写ImagesPipeline父类
class imgproPipeline(ImagesPipeline):
#该方法根据图片URL地址进行图片数据的请求
def get_media_requests(self,item,info):
yield scrapy.Request(item['src'])
#指定图片存储的路径
def file_path(self,request,response=None,info=None):
img_name = request.url.split('/')[-1].split('!')[0]
return img_name
def item_completed(self,results,item,info):
#返回给下一个即将被执行的管道类
return item
步骤4.settings.py【设置图片存储目录】
IMAGES_STORE = './images ZW' #指定图片存储的目录
整个通过Scrapy框架完成图片存储的步骤如下:
1.在spider.py中完成数据解析,同时yield item
2.在管道文件【pipelines】中自己定制一个基于ImagesPipeLine的一个管道类
-get_media_request
-file_path
-item_completed
3.在配置文件【settings.py】在:
-指定图片存储的目录:IMAGES_STORE='./imgs zw'
-指定开启的管道:自定制的管道类【如:ITEM_PIPELINES = {
'imgPro.pipelines.imgproPipeline': 1,
}
】其中imgproPileline是自己制定的管道类的名称