python - 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] ...
但我无法让它发挥作用。
有任何想法吗?
解决方案
要将其应用于您的管道,您必须在文件中查找并删除该逗号:
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()
推荐阅读
- python - 可以修改哪些参数以获得更好的 CNN 效果?
- mysql - 获取重复行但更严格
- c# - ASP.NET MVC 如何动态填充或更改属性的属性
- c# - 发现泛型参数的 NullabilityInfo?
- linux - 如何通过保留标题和第一行的列来拆分矩阵
- javascript - 如何解决滚动时出现动画的问题?
- linux - 仅向 .dts 文件添加中断
- postman - 使用 API-Key 而不是 OAuth 2.0 对 google API 进行身份验证
- c - malloc:对象 0x120e06884 的 *** 错误:未分配被释放的指针
- android - SQLITE 重复数据?