通常我知道这个错误意味着什么,但不知何故,我相信我确实通过传递了参数
我在玩scratch和管道内部的游戏,我想如果我在几个不同的网站或页面上进行抓取,我想让他们说所有的输出json文件,但当然有不同的json,这样我就可以知道哪个json属于哪个网站
所以我创建了一个服务文件夹,里面有一个名为pipeline 的文件
所以在这个pipeline.py
里面
我创建了一个低于的类
import json
import os
class JsonWriterPipeline(object):
"""
write all items to a file, most likely json file
"""
def __init__(self, filename):
print(filename) # this does prints the filename though
self.file = open(filename, 'w')
def open_spider(self, spider):
self.file.write('[')
def close_spider(self, spider):
# remove the last two char which is ',n' then add closing bracket ']'
self.file.seek(self.file.seek(0, os.SEEK_END) - 2)
self.file.write(']')
def process_item(self, item, spider):
line = json.dumps(dict(item)) + ",n"
self.file.write(line)
return item
然后在根文件夹下的原始pipeline.py
中,我有这样的
from scrape.services.pipeline import JsonWriterPipeline
JsonWriterPipeline('testing.json') # so I have passed the filename argument as `'testing.json'`
但我只是不断地得到错误,正如上面提到的,当我做print(filename)
时,它会正确打印出来。
如果我不传递文件名,而不是静态文件名,它可以很好地工作,但我当然希望它是动态的,这就是为什么我创建了一个类,这样我就可以重用它
任何人都有想法
编辑:正如下面提到的Gallaecio
所实现的那样,管道不接受参数,我在谷歌上搜索了一些答案,说管道接受参数的方式是,如果参数是通过命令行传递的,而不是在代码本身内
感谢您的建议。
我想到了一个替代方案,它不是创建新对象并在创建时传递参数。也许可以试试继承之类的东西
以下的样本
service/pipeline.py
内部
import json
import os
class JsonWriterPipeline(object):
"""
write all items to a file, most likely json file
"""
filename = 'demo.json' # instead of passing argument create variable for the class
def __init__(self):
self.file = open(self.filename, 'w+')
def open_spider(self, spider):
self.file.write('[')
def close_spider(self, spider):
# remove the last two char which is ',n' then add closing bracket ']'
self.file.seek(self.file.seek(0, os.SEEK_END) - 2)
self.file.write(']')
return
def process_item(self, item, spider):
line = json.dumps(dict(item)) + ",n"
self.file.write(line)
return item
原始pipeline.py
内部
from scrape.services.pipeline import JsonWriterPipeline
class JsonWriterPipelineA(JsonWriterPipeline):
filename = 'a.json'
def __init__(self):
super().__init__()
class JsonWriterPipelineB(JsonWriterPipeline):
filename = 'b.json'
def __init__(self):
super().__init__()
这是我能想到的另一种方式,希望这能帮助你