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)
一个类似的问题已经被问,但它的目标图像,而不是文件。
任何帮助将不胜感激。
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)
归档时间: |
|
查看次数: |
2124 次 |
最近记录: |