关于scrapy下载文件重命名的办法以及对应url没有文件后缀的办法

scrapy中负责下载文件的是class MyFilesPipeline(FilesPipeline)

  • 其中负责下载文件的方法是
def file_path(self, request, response=None, info=None):
        ## start of deprecation warning block (can be removed in the future)
        def _warn():
            from scrapy.exceptions import ScrapyDeprecationWarning
            import warnings
            warnings.warn('FilesPipeline.file_key(url) method is deprecated, please use '
                          'file_path(request, response=None, info=None) instead',
                          category=ScrapyDeprecationWarning, stacklevel=1)

        # check if called from file_key with url as first argument
        if not isinstance(request, Request):
            _warn()
            url = request
        else:
            url = request.url

        # detect if file_key() method has been overridden
        if not hasattr(self.file_key, '_base'):
            _warn()
            return self.file_key(url)
        ## end of deprecation warning block

        media_guid = hashlib.sha1(to_bytes(url)).hexdigest()  # change to request.url after deprecation
        media_ext = os.path.splitext(url)[1]  # change to request.url after deprecation
        return 'full/%s%s' % (media_guid, media_ext)

我们可以很清楚地看到 因为是下载的是文件,所以默认的response参数是为None的,因为一般来讲,文件的response就是我们下载的。我们待会说明response为None的坏处。
所以,修改文件名的办法就很显然了。在return处做文章:return 的文件路径,用了两个变量media_guidmedia_ext

  1. 其中media_guid是一个将url进行哈希加密的文件,可以修改
  2. 另一个media_ext是什么呢: os.path.splitext(url)[1]这个函数是将url作切割,不同于py里的split函数,这个函数只返回两部分,示例如下

import os
path_01='D:/User/wgy/workplace/data/notMNIST_large.tar.gar'
path_02='D:/User/wgy/workplace/data/notMNIST_large'
root_01=os.path.splitext(path_01)
root_02=os.path.splitext(path_02)
print(root_01)
print(root_02)
结果:
('D:/User/wgy/workplace/data/notMNIST_large.tar', '.gar')
('D:/User/wgy/workplace/data/notMNIST_large', '')

可以看到,就是在scrapy里这个函数就是获取后缀的。
综上,文件名可以在这边修改。

但是有一个问题,如果想要下载的文件的url是经过重定向,或者对应的url没有后缀呢。
由于网页一般会将想要请求的文件类型放在response的头部信息 content-type里,我们可以通过获取content-type信息,在进行相应的操作。这样我们就需要找到调用file_path的函数

    def file_downloaded(self, response, request, info):
        path = self.file_path(request, response=response, info=info)
        buf = BytesIO(response.body)
        checksum = md5sum(buf)
        buf.seek(0)
        self.store.persist_file(path, buf, info)
        return checksum
  • file_downloaded里,第一行就是调用了file_path函数,而且根据命名规则,十分清晰。 我们只要对上述path 做一定的修改即可。
  • 因为file_downloaded是对文件进行下载,而file_path是对文件进行存储路径的安排的,所以file_downloaded这里的response我们是可以获取相关信息的。
    获取重定向后文件后缀的方法为:
    response.headers.get('Content-Disposition') 或者 response.headers.get('Content-Type') ,如果获取不到,可以改成content-disposition 或者 content-type,举个例子
    content-disposition可能得到的是这个:
    Content-Disposition: inline;filename=Vet%20Contract%20for%20Services.pdf,直接正则获取最后的文件路径

\color{red}{Content-Disposition} 是一个扩展协议,对得到的内容进行正则处理后,可以得到后缀,一般建议先用这个。但有的并不支持这种协议
\color{red}{Content-Type}一般网站都是支持的,但是它返回的文件类型可能没法直接使用,所以建议先使用上面的那个

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,337评论 19 139
  • 本文包括:1、文件上传概述2、利用 Commons-fileupload 组件实现文件上传3、核心API——Dis...
    廖少少阅读 14,310评论 5 91
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,679评论 1 92
  • 我的第一任领导,非常犀利。他的思路敏捷而清晰,做事务实而高效,永远没有废话,永远雷厉风行。和他共事,绝对不会轻松。...
    幸福堂阅读 1,534评论 0 0
  • 前段时间在“阿文来了”看到这本书----《颠覆平庸》。在一叠书籍中一眼挑中了它,浅尝了一下,发现它是我的菜...
    小丸682阅读 1,917评论 2 3