如何解决TypeError:__init __缺少1个必需的位置参数,且参数难以传递给管道
通常我知道此错误的含义,但是我不知何故确实通过了论点
我在scrapy和管道内部玩耍,我想知道是否要通过几个不同的站点或页面进行抓取,我想让他们说所有输出json文件,但是当然使用不同的json,这样我就可以知道哪个json属于哪个json。网站
所以我创建了一个服务文件夹,里面有一个名为管道的文件
所以在这个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__()
这是我能想到的另一种方法,希望对您有帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。