Scrapy文件下载如何使用自定义文件名

Mic*_*ael 4 python scrapy scrapy-spider scrapy-pipeline

对于我scrapy项目我目前使用的FilesPipeline。下载的文件以其URL的SHA1哈希作为文件名存储。

[(True,
  {'checksum': '2b00042f7481c7b056c4b410d28f33cf',
   'path': 'full/0a79c461a4062ac383dc4fade7bc09f1384a3910.jpg',
   'url': 'http://www.example.com/files/product1.pdf'}),
 (False,
  Failure(...))]
Run Code Online (Sandbox Code Playgroud)

如何使用自定义文件名存储文件?

在上面的示例中,我希望文件名为“ product1_0a79c461a4062ac383dc4fade7bc09f1384a3910.pdf”,因此我保持唯一性,但使文件名可见。

首先,我探索了pipelines.py我的项目,但没有取得太大的成功。

import scrapy
from scrapy.pipelines.images import FilesPipeline
from scrapy.exceptions import DropItem

class MyFilesPipeline(FilesPipeline):

    def file_path(self, request, response=None, info=None):
        return request.meta.get('filename','')

    def get_media_requests(self, item, info):
        file_url = item['file_url']
        meta = {'filename': item['name']}
        yield Request(url=file_url, meta=meta)
Run Code Online (Sandbox Code Playgroud)

并在我的 settings.py

ITEM_PIPELINES = {
    #'scrapy.pipelines.files.FilesPipeline': 300
    'io_spider.pipelines.MyFilesPipeline': 200
}
Run Code Online (Sandbox Code Playgroud)

一个类似的问题已经被问,但它的目标图像,而不是文件。

任何帮助将不胜感激。

Dju*_*nzu 6

file_path应该返回文件的路径。在代码中,file_path返回item['name'],这将是文件的路径。请注意,默认情况下会file_path 计算SHA1哈希值。所以你的方法应该是这样的:

def file_path(self, request, response=None, info=None):
    original_path = super(MyFilesPipeline, self).file_path(request, response=None, info=None)
    sha1_and_extension = original_path.split('/')[1] # delete 'full/' from the path
    return request.meta.get('filename','') + "_" + sha1_and_extension
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这是我期待的帮助 - 在我的上下文中只是你的代码的一个小问题,最后一个像用字符串连接列表所以我必须明确选择列表中的第一项 `return request.meta.get( '文件名','')[0] + "_" + sha1_and_extension` (2认同)