2017-11-19 2 views
0

내가 좋아하는 출력하게해야 Scrapy 스크립트 작업입니다 :Scrapy에서 사용자 정의 JSON 출력을 생성하는 방법은 무엇입니까?

{ 
    "state": "FL", 
    "date": "2017-11-03T14:52:26.007Z", 
    "games": [ 
    { 
     "name":"Game1" 
    }, 
    { 
     "name":"Game2" 
    } 
    ] 
} 

을하지만 scrapy crawl items -o data.json -t json를 실행할 때 날 위해 아래와 같이하고 있습니다. state

[ 
{"state": "CA", "games": [], "crawlDate": "2014-10-04"}, 
{"state": "CA", "games": [], "crawlDate": "2014-10-04"}, 
] 

코드를의 반복은 아래와 같습니다 :

수입 scrapy는

items.py

스파이더 파일에서
class Item(scrapy.Item): 
state = scrapy.Field() 
games = scrapy.Field() 

, item 클래스라고한다

:

item = Item() 
item['state'] = state 
item['Date'] = '2014-10-04' 
item['games'] = games 

이 코드는 완전한 코드는 아니지만 내가 무엇에 관한 아이디어인지 알고 있어야합니다.

답변

0

Ref. https://stackoverflow.com/a/43698923/8964297

당신은이 같은 자신의 파이프 라인 작성을 시도 할 수

:

ITEM_PIPELINES = { 
    'YourSpiderName.pipelines.JsonWriterPipeline': 300, 
} 

: 다음을 포함하는 그런 다음 settings.py을 수정

import json 


class JsonWriterPipeline(object): 
    def open_spider(self, spider): 
     self.file = open('scraped_items.json', 'w') 
     # Your scraped items will be saved in the file 'scraped_items.json'. 
     # You can change the filename to whatever you want. 
     self.file.write("[") 

    def close_spider(self, spider): 
     self.file.write("]") 
     self.file.close() 

    def process_item(self, item, spider): 
     line = json.dumps(
      dict(item), 
      indent = 4, 
      sort_keys = True, 
      separators = (',', ': ') 
     ) + ",\n" 
     self.file.write(line) 
     return item 

:

pipelines.py 파일에이를 넣어 YourSpiderName을 거미의 정확한 이름으로 변경하십시오.

파일이 파이프 라인에 의해 직접 기록되므로 명령 줄 매개 변수 -o-t과 함께 파일 및 형식을 지정할 필요가 없습니다.

희망이 있으면 원하는 것에 더 가까워지기를 바랍니다.

+0

항목을 가져 오면이 작업이 실행됩니까? 'scraped_items.json'이란 무엇입니까? – Volatil3

+0

@ Volatil3, 파이프 라인은 가져온 각 항목에 대해 트리거되어 JSON 파일에 기록됩니다. 'scraped_items.json'은 출력 파일의 이름입니다. 파일 이름 (및 경로)을 원하는대로 변경할 수 있습니다. –

관련 문제