1. 程式人生 > >scrapy爬取圖片並自定義圖片名字

scrapy爬取圖片並自定義圖片名字

  前言
  
  Scrapy使用ImagesPipeline類中函式get_media_requests下載到圖片後,預設的圖片命名為圖片下載連結的雜湊值,例如:它的下載連結是,雜湊值為7710759a8e3444c8d28ba81a4421ed,那麼最終的圖片下載到指定路徑後名稱為7710759a8e3444c8d28ba81a4421ed.JPG。想要自定義圖片名稱則需要藉助ImagesPipeline類中item_completed()函式來重新命名。
  
  2   爬蟲過程
  
  爬蟲過程就不贅述了,本文章重點介紹如何自定義圖片名稱。爬蟲執行後獲得的圖片如下圖:
  
  3   自定義圖片名稱具體方法
  
  3.1 自定義圖片名稱程式碼
  
  複製程式碼
  
  import os
  
  from  harry.settings import IMAGES_STORE as IMGS
  
  from scrapy.pipelines.images import ImagesPipeline
  
  from scrapy import Request
  
  class HarryPipeline(object):
  
  def process_item(self, item, spider):
  
  return item
  
  class HarryDownLoadPipeline(ImagesPipeline):
  
  def get_media_requests(self, item, info):
  
  for imgurl in item['img_url']:
  
  yield Request(imgurl)
  
  def item_completed(self, results, item, info):
  
  print ('******the results is********:',results)
  
  os.rename(IMGS + '/' + results[0][1]['path'], IMGS + '/' + item['img_name'])
  
  def __del__(self):
  
  #完成後刪除full目錄
  
  os.removedirs(IMGS + '/' + 'full')
  
  複製程式碼
  
  注:對於def __del__(self)函式可要可不要,因為重新命名過程是攜帶路徑重新命名,所以預設生成的full資料夾就為空,只是順手刪除空資料夾(如果裡面有檔案存在是刪除不了的)
  
  3.2 自定義圖片名稱程式碼詳細解析
  
  3.2.1    get_media_requests函式
  
  get_media_requests方法的原型為:
  
  def item_completed(self, results, item, info):
  
  if isinstance(item, dict) or self.images_result_field in item.fields:
  
  item[self.images_result_field]www.michenggw.com = [x for ok, x in results if ok]
  
  return item
  
  可以看到get_media_requests有三個引數,
  
  第一個是self,這個不必多說;
  
  第二個是 item,這個就是 spiders傳遞過來的 item
  
  第三個是 info,看名字就知道這是用來儲存資訊的,至於是什麼資訊,info其實是一個用來儲存儲存圖片的名字和下載連結的列表
  
  3.2.2    Item_completed函式
  
  item_completed方法的原型如下:
  
  def item_completed(self, results, item, info):
  
  if isinstance(item, dict) or self.images_result_field in item.fields:
  
  item[self.images_result_field] = [x for ok, x in results www.gouyiflb.cn if ok]
  
  return item
  
  注意到 item_completed裡有個 results引數,results引數儲存了圖片下載的相關資訊,將他print看看具體資訊:
  
  [(True, {'url': 'http://www.tongqt178.com img.www.dasheng178.com ivsky.com/img/bizhi/pre/201101/10/harry_potter5-015.jpg', 'path': 'full/539c5914730497b094e5c98bfdfe19b65f5.jpg', 'checksum': '37d23ffb0ab983ac2da9a9d'})]
  
  真實結構為一個list [(DownLoad_success_or_yongshiyule178.com failure),dict],字典中含有三個鍵:1、'url':圖片路徑 2、'path':圖片下載後的儲存路徑 3、'checksum':校驗碼
  
  從中我們可以看到只要我們修改字典中圖片儲存路徑(路徑詳細到圖片名稱)的值,那麼我們就能自定義圖片名稱。
  
  關鍵程式碼為:
  
  os.rename(IMGS + '/' + results[0][1]['path'], IMGS + '/' + item['img_name'])
  
  解釋:rename函式,results[0][1]['path']意思就是:在result這個list中找到圖片的名稱,其中我們也可以看到這個圖片的位置是絕對路徑,所以需要攜帶路徑IMGS修改。