【问题标题】:JSON.Dump doesn't capture the whole streamJSON.Dump 不捕获整个流
【发布时间】:2016-10-13 19:29:45
【问题描述】:

所以我有一个简单的爬虫,它爬取 3 个商店位置页面并将商店的位置解析为 json。我 print(app_data['stores']) 它打印了所有三页商店。但是,当我尝试将其写出时,我只能将三页中的一页随机写入我的 json 文件。我希望将流中的所有内容写入文件。任何帮助都会很棒。代码如下:

import scrapy
import json
import js2xml

from pprint import pprint

class StlocSpider(scrapy.Spider):
    name = "stloc"
    allowed_domains = ["bestbuy.com"]
    start_urls = (
        'http://www.bestbuy.com/site/store-locator/11356',
        'http://www.bestbuy.com/site/store-locator/46617',
        'http://www.bestbuy.com/site/store-locator/77521'
    )

    def parse(self, response):
        js = response.xpath('//script[contains(.,"window.appData")]/text()').extract_first()
        jstree = js2xml.parse(js)
        # print(js2xml.pretty_print(jstree))

        app_data_node = jstree.xpath('//assign[left//identifier[@name="appData"]]/right/*')[0]
        app_data = js2xml.make_dict(app_data_node)
        print(app_data['stores'])

        for store in app_data['stores']:
            yield store

        with open('stores.json', 'w') as f:
            json.dump(app_data['stores'], f, indent=4)

【问题讨论】:

  • 每次调用parse() 时都会覆盖文件。您需要将所有结果收集到一个列表中,并将整个列表写入文件。

标签: python json scrapy js2xml


【解决方案1】:

您每次都打开文件进行写入,但您想追加。尝试将最后一部分更改为:

with open('stores.json', 'a') as f:
    json.dump(app_data['stores'], f, indent=4)

'a' 在哪里打开文件以进行追加。

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2017-06-11
    • 2013-10-01
    相关资源
    最近更新 更多