3つのストアロケーションページをクロールし、ストアの場所をjsonに解析する単純なクローラがあります。私は印刷します(app_data ['stores'])、それは店舗の3つのページすべてを印刷します。しかし、私はそれを書き込もうとすると、3つのページのうちの1つを無作為にjsonファイルに書き込むだけです。ストリームに書かれたすべてのものをファイルに書きたいのですが。どんな助けも素晴らしいだろう。コードは次のとおりです。JSON.Dumpはストリーム全体をキャプチャしません
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()'を呼び出すたびにファイルを上書きしています。すべての結果をリストにまとめ、リスト全体をファイルに書き込む必要があります。 – Barmar