我嘗試了不同的方法後得到了一個工作解決方案。 因爲在我的特殊情況下,我將輸出轉儲爲文件,特別是bz2文件。我在打開文件之前和之後定製了一個FileFeedStorage
來完成這項工作。請參閱以下代碼:
from scrapy.contrib.feedexport import FileFeedStorage
import os
import bz2
MB = 1024 * 1024
class Bz2FileFeedStorage(FileFeedStorage):
IN_PROGRESS_MARKER = ".inprogress"
def __init__(self, uri):
super(Bz2FileFeedStorage, self).__init__(uri)
self.in_progress_file = self.path + Bz2FileFeedStorage.IN_PROGRESS_MARKER
def open(self, spider):
dirname = os.path.dirname(self.path)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
return bz2.BZ2File(self.in_progress_file, "w", 10 * MB)
def store(self, file):
super(Bz2FileFeedStorage, self).store(file)
os.rename(self.in_progress_file, self.path)
謝謝。使用信號是一個好主意,但是想知道它如何與現有管道配合使用?具體而言,我不確定是否可以在蜘蛛的開頭和結尾重命名文件。它不會破壞導出器輸出文件處理程序嗎? – Andy
如果您使用項目管道來編寫輸出文件,則可能需要使用spider_open/spider_close回調:http://doc.scrapy.org/en/latest/topics/item-pipeline.html#writing-yourown -Item流水線 – sardok