学习时间:9:00——12:00 15:00——16:30
图片数据爬取之ImagesPipeline
—基于scrapy爬取字符串类型的数据和爬取图片类型的数据区别?
—字符串:只需要基于xpath进行解析且提交管道进行持久化存储
—图片:xpath解析出图片src的属性值。单独的对图片地址发起请求获取图片二进制类型的数据
—ImagesPipeline:
—只需要将img的src的属性值进行解析,提交到管道,管道就会对图片的src进行请求发送获取图片的二进制数据,还会进行持久化存储
需求:爬职站长素材中的高清图片
一使用流程:
一数据解析(图片的地址)
一将存储图片地址的item提交到制定的管道类
—在管道文件中自定制一个基于ImagesPipeLine的一个管道类
—get_media_request
— file_path
— item completed—
—在配置文件中:
一指定图片存储的目录:IMAGES_STORE = './imgs'
—指定开启的管道:自定制的管道类
代码如下:
img.py
import scrapy
from imgsPro.items import ImgsproItem
class ImgSpider(scrapy.Spider):
name = 'img'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://sc.chinaz.com/tupian/']
def parse(self, response):
div_list = response.xpath('//div[@id="container"]/div')
for div in div_list:
src = div.xpath('./div/a/img/@src').extract_first()
img_src = src.replace('_s.jpg','.jpg')
img_src = 'https:' + img_src
# 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:
img_src = scrapy.Field()
pipelines.py
import scrapy
from itemadapter import ItemAdapter
from scrapy.pipelines.images import ImagesPipeline
# class ImgsproPipeline:
# def process_item(self, item, spider):
# return item
class imgsPileLine(ImagesPipeline):
#根据图片地址进行图片数据的请求
def get_media_requests(self, item, info):
yield scrapy.Request(item['img_src'])
#指定图片存储的路径
def file_path(self, request, response=None, info=None, *, item=None):
imgName = request.url.split('/')[-1]
return imgName
def item_completed(self, results, item, info):
return item #返回给下一个即将执行的管道类
settings.py
USER_AGENT = 'xxx'
LOG_LEVEL = 'ERROR'
ROBOTSTXT_OBEY = False
ITEM_PIPELINES = {
'imgsPro.pipelines.imgsPileLine': 300,
}
#指定图片存储的目录
IMAGES_STORE = './imgs'
MEDIA_ALLOW_REDIRECTS =True
注意:
item['src']会报错,不能用src
图片一开始的src仅为缩略图src,并不是高清的src,对比可知,高清图片的src仅是在缩略图src后加上_s即可,并且src不完整,要在前面拼接上 https:
如果既没有报错也没有反应,那么要安装pillow
类名要注意统一,注意拼写错误
中间件
—下载中间件
—位置:引擎和下载器之间
—作用:批量拦截到整个工程所有的请求和响应
—拦截请求:UA伪装:process_request
代理ip:process_exception:return request
—拦截响应:篡改响应数据、响应对象