系列文章列表:
scrapy爬虫学习系列一:scrapy爬虫环境的准备:
scrapy爬虫学习系列二:scrapy简单爬虫样例学习:
scrapy爬虫学习系列三:scrapy部署到scrapyhub上:
scrapy爬虫学习系列四:portia的学习入门:
scrapy爬虫学习系列五:图片的抓取和下载:
scrapy爬虫学习系列六:官方文档的学习:
注意: 我自己新建的一个QQ群(新建的),欢迎大家加入一起学习一起进步 ,群号646187336
这篇文章主要对一个车标网()的图片进行抓取,并按照图片的alt属性值去设置输出图片命名。
本文的最终源码下载地址(github):
1.创建工程和爬虫
C:\Users\Administrator>e:E:\>cd scrapytestE:\scrapytest>scrapy startproject cariconNew Scrapy project 'caricon', using template directory 'C:\\Program Files\\Anaconda3\\lib\\site-packages\\scrapy\\templates\\project', created in: E:\scrapytest\cariconYou can start your first spider with: cd caricon scrapy genspider example example.comE:\scrapytest>cd cariconE:\scrapytest\caricon>scrapy genspider car car.bitauto.com/qichepinpaiCreated spider 'car' using template 'basic' in module: caricon.spiders.car
4.修改item
添加字段,修改后为如下内容:
# -*- coding: utf-8 -*-# Define here the models for your scraped items## See documentation in:# http://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass CariconItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() image_urls = scrapy.Field() images = scrapy.Field() alt = scrapy.Field()
- image_urls : 作为项目的图片网址(需要我们指定url)。
- images :下载的影像信息(这个字段不是我们填充的)。
注意: 上面的alt字段是我自己加的,image_urls ,images这2个字段是请求图片的默认字段,必须要有的,建议使用默认字段。你要是喜欢折腾可以参考这个网址:
3.修改爬虫
这里我们先使用火狐浏览器的Firefinder插件找找我们需要提取的图片,图片如下:
# -*- coding: utf-8 -*-# Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlclass CariconPipeline(object): def process_item(self, item, spider): return itemfrom scrapy.contrib.pipeline.images import ImagesPipelinefrom scrapy.http import Requestfrom scrapy.exceptions import DropItemimport osclass MyImagesPipeline(ImagesPipeline): def file_path(self, request, response=None, info=None): #url_file_name= request.url.split('/')[-1] #image_guid = hashlib.sha1(to_bytes(url)).hexdigest() alt_name=request.meta["alt"] return 'full/%s%s' % (alt_name, os.path.splitext(request.url)[-1]) def get_media_requests(self, item, info): yield Request(item["image_urls"][0], meta={ 'alt':item["alt"]})
代码简介:通常我们使用官方的那个imagepipeline导出的文件是SHA1 hash 你的url作为文件名,很难区别啊,这里使用到了request方法的meta参数,把我们的图片的alt属性传递过去,这样我们返回文件名的时候就可以使用这个alt的名字来区别了。(但是如果alt重复又替换了原来的图片的)
注意,firefinder这个插件依赖与firebug的,你可以在你的浏览器找类似firefinder的工具。
6.修改setttings.py文件
修改下面片段为如下内容:
ITEM_PIPELINES = { 'caricon.pipelines.MyImagesPipeline': 300,}
IMAGES_STORE = r'e:\test\pic\'
当然我们这里可以使用官方的imagepipeline(scrapy.pipelines.images.ImagesPipeline)
6.运行爬虫
E:\scrapytest\caricon>scrapy crawl car
7.查看结果