Scrapy圖片自動下載配置

在setting.py中配置基本信息

IMAGES_URLS_FIELD = "front_image_url"
# 獲取當前文件路徑
project_dir = os.path.abspath(os.path.dirname(__file__))
# 設置圖片保存路徑
IMAGES_STORE = os.path.join(project_dir, 'images')

同時打開

ITEM_PIPELINES = {

     # 自動下載圖片配置,這個是scrapy自帶的
     'scrapy.pipelines.images.ArticleImagePipeline':1,
}

但是很多情況下我們需要獲取我們保存的圖片的路徑的(包括名稱,這樣我們就可定位到不同item對應的圖片),這時候我們需要自定義下載類

進入pipelines.py中添加下面的方法

# 自定義Pipeline
class ArticleImagePipeline(ImagesPipeline):
    def item_completed(self, results, item, info):
        for ok, value in results:
            image_file_path = value["path"]  # 獲取文件路徑
        item["front_image_path"] = image_file_path
        return item

        # 可以通通過reslts獲取保存路徑

然後需要在setting中改動

發佈了55 篇原創文章 · 獲贊 58 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章