그래서 3 개의 위치 페이지를 크롤링하고 json에 대한 상점 위치를 파싱하는 간단한 크롤러가 있습니다. 나는 인쇄를하고 (app_data [ 'stores']) 3 페이지의 모든 상점을 인쇄합니다. 그러나, 나는 그것을 쓰려고 할 때만 세 페이지 중 하나를 무작위로 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