首页 > 解决方案 > Python Scrapy Pipeline 编辑最后一项?

问题描述

我在 Scrapy 中使用管道将抓取的结果输出到 JSON 文件中。管道在每个被抓取的项目之后放置一个逗号,但是,我想删除最后一个项目的逗号。有没有办法做到这一点?

这是管道:

class ExamplePipeline(object):
def open_spider(self, spider):
    self.file = open('example.json', 'w')
    self.file.write("[")

def close_spider(self, spider):
    self.file.write("]")
    self.file.close()

def process_item(self, item, spider):
    line = json.dumps(
        dict(item),
        indent = 4,
        sort_keys = True,
        separators = (',', ': ')
    ) + ",\n"
    self.file.write(line)
    return item

示例输出如下所示:

[
{
    "item1": "example",
    "item2": "example"
},
{
    "item1": "example",
    "item2": "example"
},
]

查找最后一项而不给它逗号分隔符的python方法是什么?我以为我可以做类似的事情,if item[-1] ...但我无法让它发挥作用。

有任何想法吗?

标签: pythonscrapyscrapy-pipeline

解决方案


要将其应用于您的管道,您必须在文件中查找并删除该逗号:

请参阅相关的 Python - 删除文件中的最后一个字符

class ExamplePipeline(object):

    def close_spider(self, spider):
        # go back 2 characters: \n and ,
        self.file.seek(-2, os.SEEK_END)
        # cut trailing data
        self.file.truncate()
        # save
        self.file.write("]")
        self.file.close()

推荐阅读