scrapy中的ImagePipeline下載圖片到本地、並提取本地的保存地址

  • 通過scrapy內置到ImagePipeline下載圖片到本地
    1. 在settings中打開 ITEM_PIPELINES的註釋,並在這裏面加入
      'scrapy.pipelines.images.ImagesPipeline':5,
      #後面的數字代表執行優先級 ,當執行pipeine的時候會按照數字由小到大執行
    2. 在settings中加入
      IMAGES_URLS_FIELD ="image_url"  #image_url是在items.py中配置的網絡爬取得圖片地址
      #配置保存本地的地址
      project_dir=os.path.abspath(os.path.dirname(__file__))  #獲取當前爬蟲項目的絕對路徑
      IMAGES_STORE=os.path.join(project_dir,'images')  #組裝新的圖片路徑
       還有很多設置有特殊需要的話可以用哦 (詳情可以去imagepipeine源碼查看)
      
         IMAGES_MIN_HEIGHT=100   #設定下載圖片的最小高度
      
         IMAGES_MIN_WIDTH=100  #設定下載圖片的最小寬度

       

      1. 可能會報錯:

        ModuleNotFoundError: No module named 'PIL'
        1.  這時候安裝pip install pillow庫就可以了

  • 獲取圖片保存本地的地址
    1. 下載圖片,如果想獲取圖片保存本地的地址,那麼就需要重寫ImagesPipeline,並且在settings中調用重寫的pipeline
      #既然要重寫,記得提前引入
      from scrapy.pipelines.images import ImagesPipeline
      
      class ArticleImagePipeline(ImagesPipeline):
      # 重載ImagePipeline中的item_completed方法,獲取下載地址
      def item_completed(self, results, item, info):
      
        for ok,value in results:   #通過斷點可以看到圖片路徑存在results內
      
          image_file_path=value['path'] #將路徑保存在item中返回
      
          item['front_image_path']=image_file_path
        return item

       

    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章