首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python/Scrapy:自定义管道没有使用自定义文件名的效果/下载文件

Python/Scrapy:自定义管道没有使用自定义文件名的效果/下载文件
EN

Stack Overflow用户
提问于 2019-02-21 09:44:46
回答 1查看 870关注 0票数 3

这是我的initial question的后续问题.我想下载PDF并将它们保存在带有自定义文件名的硬盘上。

对于自定义文件名,我根据这个pipelines.pyrecommendation中尝试了以下代码

代码语言:javascript
运行
复制
class PrangerPipeline(object):
    def process_item(self, item, spider):
        return item

    def file_path(self, request, response=None, info=None):
        original_path = super(PrangerPipeline, 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

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

在我的settings.py中有:

代码语言:javascript
运行
复制
ITEM_PIPELINES = {
    'pranger.pipelines.PrangerPipeline': 1,
    'scrapy.pipelines.files.FilesPipeline': 2,
}

但是这些文件只保存在SHA1 1-散列中,例如:一个8569143c987cdd43dd1f6d9a6f98b7a6fbc284.PDF,所以我的自定义file_path函数似乎不被Scrapy使用。

当我评论出这一行时

代码语言:javascript
运行
复制
'scrapy.pipelines.files.FilesPipeline': 2,

不会下载任何东西。

我很困惑..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-21 09:49:02

您的问题是您的自定义管道不是真正的文件管道,因此它什么也不做。您需要子类原始FilesPipeline,然后在设置中只使用PrangerPipeline

例如:

pipelines.py

代码语言:javascript
运行
复制
from scrapy.pipelines.files import FilesPipeline

class PrangerPipeline(FilesPipeline):

    # Don't override process_item. The parent class handles it.

    def file_path(self, request, response=None, info=None):
        # ...

    def get_media_requests(self, item, info):
        # ...

settings.py

代码语言:javascript
运行
复制
ITEM_PIPELINES = {
    'pranger.pipelines.PrangerPipeline': 1,
}

请参阅我在这里使用ImagesPipeline的示例:

Unable to rename downloaded images through pipelines without the usage of item.py

Trouble renaming downloaded images in a customized manner through pipelines

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54803908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档