我在一个 scrapy 项目中有多个蜘蛛。
我想为每个蜘蛛编写一个单独的输出文本文件,其中包含蜘蛛名称和时间戳。
当我有一个蜘蛛时,我正在 __init
创建文件方法,但现在我正在尝试这样,upromise将生成两个输出文件,而其他只会生成一个。
class MallCrawlerPipeline(object):
def spider_opened(self, spider):
self.aWriter = csv.writer(open('../%s_%s.txt' % (spider.name, datetime.now().strftime("%Y%m%d_%H%M%S")), 'wb'),
delimiter=',', quoting=csv.QUOTE_MINIMAL)
self.aWriter.writerow(['mall', 'store', 'bonus', 'per_action', 'more_than','up_to', 'deal_url', 'category'])
if 'upromise' in spider.name:
self.cWriter = csv.writer(
open('../%s_coupons_%s.txt' % (spider.name, datetime.now().strftime("%Y%m%d_%H%M%S")), 'wb'),
delimiter=',', quoting=csv.QUOTE_MINIMAL)
self.cWriter.writerow(['mall', 'store', 'bonus', 'per_action', 'more_than','up_to', 'deal_url', 'category'])
def process_item(self, item, spider):
self.aWriter.writerow([item['mall'], item['store'], item['bonus'], item['per_action'],
item['more_than'], item['up_to'], item['deal_url'], item['category']])
return item
但我面临这个错误:
File "C:\Users\akhter\Dropbox\akhter\mall_crawler\mall_crawler\pipelines.py", line 24, in process_item
self.aWriter.writerow([item['mall'], item['store'], item['bonus'], item['per_action'],
exceptions.AttributeError: 'MallCrawlerPipeline' object has no attribute 'aWriter'
如有任何帮助,我们将不胜感激。提前致谢。
最佳答案
你确定你一直在运行obj.spider_opened(...)
之前obj.process_item(...)
?看来您不是,因为在第一个方法调用之后,该属性应该已添加到对象中。
如果始终需要第一个方法调用,也许将其移至 __init__
是有意义的顺便说一下,或者从那里调用它。
关于python - 将文本文件写入管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9608391/