【问题标题】:How to handle image filename duplication in scrapy image download如何处理scrapy图像下载中的图像文件名重复
【发布时间】:2013-05-29 05:49:15
【问题描述】:

Scrapy 使用 sha1 生成随机图像文件名。发生重复时,它将覆盖文件,导致现有图像文件丢失。 是否可以编写额外的代码(例如:重写类)来处理重复。例如:不断生成新的随机文件名,直到找不到重复? 如果是,请提供代码示例?

---老问题: 它是否检查以确保 images_store 文件夹下所有图像文件的文件名唯一性? Scrapy 在下载图像时使用 sha1 生成随机文件名。 Sha1 提供了良好的唯一性,但从概率上讲,存在重复的机会。

【问题讨论】:

标签: scrapy sha1 hash-code-uniqueness


【解决方案1】:

不确定这是不是最好的解决方案,但是如果您基于 ImagesPipeline 管道创建自定义管道并像这样覆盖 image_key 方法会怎么样(虽然,还没有测试过):

import hashlib
import os
import random
import string
from scrapy.contrib.pipeline.images import ImagesPipeline


class CustomImagesPipeline(ImagesPipeline):
    def image_key(self, url):
        image_guid = hashlib.sha1(url).hexdigest()

        # check if image already exists and add some random char to the file name
        path_format = 'full/%s.jpg'
        while True:
            path = path_format % image_guid
            if os.path.exists(path):
                image_guid = image_guid + random.choice(string.letters)
            else:
                break

        return path

这只是一个示例 - 您可能希望改进文件名更改逻辑。此外,您应该对 thumb_key 方法执行相同的操作。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    你不应该关心它!

    Scrapy 使用图像 url sha1。为了有 50% 的概率找到 SHA1 冲突,您需要大约 2^80 个项目。所以,除非你要爬取 2^80 张图片,否则图片文件名重复的几率小于 50%。事实上,您可以抓取超过 1 万亿张图像,并且简单地忽略文件名重复,因为机会微乎其微。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 2017-02-06
      • 2011-07-01
      相关资源
      最近更新 更多