【问题标题】:Scrapy json output missing commaScrapy json输出缺少逗号
【发布时间】:2020-05-13 00:50:11
【问题描述】:

我是 Scrapy 的新手,并且一直在尝试解决这个问题。提前致谢。 我想获得来自不同页面的链接列表。每个 parse 方法都会生成一个带有链接列表的对象,但输出文件只是转储这些对象而不将它们放入列表中,因此它不是有效的 json。

输出是

{"links": *list of links*}
{"links": *list of links*}

但我想在列表中看到它

[{"links": *list of links*},
{"links": *list of links*}]

使用$ scrapy crawl links -o links.json 运行它

class LinksSpider(scrapy.Spider) :
    name = "links"

    def start_requests(self):
        start_urls = [
            "https://www.snerpa.is/net/isl/isl-th.htm",
            "https://www.snerpa.is/net/snorri/heimskri.htm"
        ]
        for url in start_urls:
            yield scrapy.Request(url=url, callback=self.parse)


    def parse(self, response) :
        linksList = []
        for link in response.xpath("//a/@href"):
            if link.get().index("/") < 2:
                linksList.append("https://www.snerpa.is/net/isl" + link.get()[1:])
        yield {
            "links": linksList
        }

编辑: Scrapy 2.1.0版

我发现我做错了什么。我之前复制了一个sn-p并把它放在settings.py中 改变这个

from scrapy.exporters import JsonLinesItemExporter
class MyJsonLinesItemExporter(JsonLinesItemExporter):
    def __init__(self, file, **kwargs):
        super(MyJsonLinesItemExporter, self).__init__(file, ensure_ascii=False, **kwargs)

FEED_EXPORTERS = {
    'jsonlines': 'postscrape.settings.MyJsonLinesItemExporter',
    'jl': 'postscrape.settings.MyJsonLinesItemExporter',
    'json': 'postscrape.settings.MyJsonLinesItemExporter'
}

到这里……

from scrapy.exporters import JsonItemExporter
class MyJsonItemExporter(JsonItemExporter):
    def __init__(self, file, **kwargs):
        super(MyJsonItemExporter, self).__init__(file, ensure_ascii=False, **kwargs)

FEED_EXPORTERS = {
    'jsonlines': 'postscrape.settings.MyJsonItemExporter',
    'jl': 'postscrape.settings.MyJsonItemExporter',
    'json': 'postscrape.settings.MyJsonItemExporter'
}

修复了问题

【问题讨论】:

  • 你的scrapy版本是多少?

标签: json python-3.x web-scraping scrapy


【解决方案1】:

Scrapy 中有不同的 JSON 导出器:JsonItemExporter 和 JsonLinesItemExporter。默认情况下,scrapy 会尝试使用文件扩展名猜测您想要什么输出。 看起来您有类似命令的输出:

$ scrapy crawl links -t jsonlines -o links.json

我不确定旧的scrapy 版本,但在 2.0.1 中,这个命令可以像你想要的那样工作:

$ scrapy crawl links -t json -o links.json

【讨论】:

  • 非常感谢!这个答案让我意识到我做错了什么,见上文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
相关资源
最近更新 更多