所以我有一个简单的爬虫程序,它可以爬网3个商店位置页面,并将商店的位置解析为json。我打印(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)
每次都要打开文件进行写入,但要追加。尝试将最后一部分改为:
其中
'a'
打开要追加的文件。你知道吗相关问题 更多 >
编程相关推荐