Skip to main content
 首页 » 编程设计

python之如何更改保存图片的目录,scrapy

2025年05月04日9yyy_WW

我正在从网页上抓取图片。 我有几个图片列表:

list_1,list_2,list_3  

这些列表中的每一个都对应一个不同的类别,到目前为止所有图像都保存在同一目录中,即在设置文件中指定的目录

IMAGES_STORE = '/home/user/Desktop/folder1/folder2' 

我想将每个列表中的图像保存在不同的 forder 中。

请您参考如下方法:

这是回答here和 here .

基本上重写 item_completed 方法,并根据图像来自哪个列表包含您要将图像保存到何处的逻辑。

def item_completed(self, results, item, info): 
 
    for result in [x for ok, x in results if ok]: 
        path = result['path'] 
        slug = slugify(item['designer']) 
 
 
        settings = get_project_settings() 
        storage = settings.get('IMAGES_STORE') 
 
        target_path = os.path.join(storage, slug, os.path.basename(path)) 
        path = os.path.join(storage, path) 
 
        # If path doesn't exist, it will be created 
        if not os.path.exists(os.path.join(storage, slug)): 
            os.makedirs(os.path.join(storage, slug)) 
 
        if not os.rename(path, target_path): 
            raise DropItem("Could not move image to target folder") 
 
    if self.IMAGES_RESULT_FIELD in item.fields: 
        item[self.IMAGES_RESULT_FIELD] = [x for ok, x in results if ok] 
    return item