scrapy图片爬取
爬取字符串和爬取图片的区别
- 字符串:基于xpath进行解析提价管道进行持久化存储
- 图片:xpath解析出图片src属性,对图片地址发起请求获取图片二进制类型数据
ImagesPipeline
将img的src属性进行解析,提交到管道,管道会对src进行请求发送获取图片的二进制类型的数据且进行持久化存储
使用流程
- 数据解析。解析出图片地址。
- 将存储图片地址的item提交到imagespipeline管道类
- 在管道文件中自定义一个基于ImagesPipeline的管道类(重写三个方法)
- 配置文件中指定存储目录,指定开启管道
爬虫文件
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'
爬取结果