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__()

这是我能想到的另一种方法,希望对您有帮助

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...