Skip to main content
 首页 » 编程设计

python之如何将 scrapy 图像下载到动态文件夹中

2024年10月25日9dflying

我可以通过 scrapy 下载图像到“完整”文件夹,但每次运行 scrapy 时,我都需要使目标文件夹的名称动态化,例如 full/session_id。

有什么办法吗?

请您参考如下方法:

我还没有使用过 ImagesPipeline,但是 following the documentation ,我会覆盖 item_completed(results, items, info)。

原来的定义是:

def item_completed(self, results, item, info): 
    if self.IMAGES_RESULT_FIELD in item.fields: 
        item[self.IMAGES_RESULT_FIELD] = [x for ok, x in results if ok] 
    return item 

这应该会为您提供包含路径的下载图像的结果集(似乎一个项目上可以有很多图像)。

如果您现在在子类中更改此方法以在设置路径之前移动所有文件,它应该可以正常工作。您可以在项目上设置目标文件夹,例如 item['session_path']。在从蜘蛛返回/放弃您的项目之前,您必须在每个项目上设置此设置。

重写方法的子类看起来像这样:

import os, os.path 
from scrapy.contrib.pipeline.images import ImagesPipeline 
 
class SessionImagesPipeline(ImagesPipeline): 
    def item_completed(self, results, item, info): 
        # iterate over the local file paths of all downloaded images 
        for result in [x for ok, x in results if ok]: 
            path = result['path'] 
            # here we create the session-path where the files should be in the end 
            # you'll have to change this path creation depending on your needs 
            target_path = os.path.join((item['session_path'], os.basename(path))) 
 
            # try to move the file and raise exception if not possible 
            if not os.rename(path, target_path): 
                raise ImageException("Could not move image to target folder") 
 
            # here we'll write out the result with the new path, 
            # if there is a result field on the item (just like the original code does) 
            if self.IMAGES_RESULT_FIELD in item.fields: 
                result['path'] = target_path 
                item[self.IMAGES_RESULT_FIELD].append(result) 
 
        return item 

更好的方法是不在 item 中设置所需的 session 路径,而是在 scrapy 运行期间的配置中。为此,我认为您必须了解如何在应用程序运行时设置配置,并且必须覆盖构造函数。