2013-08-11 4 views
23

Scrapy를 사용하여 JSON을 반환하는 웹 요청을 긁는 방법은 무엇입니까? 예를 들어, JSON은 다음과 같이 보일 것이다 : 나는 특정 항목 (위의 예 namefax)를 긁어 CSV로 저장하고자하는 것입니다Scrapy로 JSON 응답 긁음

{ 
    "firstName": "John", 
    "lastName": "Smith", 
    "age": 25, 
    "address": { 
     "streetAddress": "21 2nd Street", 
     "city": "New York", 
     "state": "NY", 
     "postalCode": "10021" 
    }, 
    "phoneNumber": [ 
     { 
      "type": "home", 
      "number": "212 555-1234" 
     }, 
     { 
      "type": "fax", 
      "number": "646 555-4567" 
     } 
    ] 
} 

.

답변

39

그것은 사용하는 것과 동일합니다 Scrapy의 HtmlXPathSelector html로 응답합니다.

class MySpider(BaseSpider): 
    ... 


    def parse(self, response): 
     jsonresponse = json.loads(response.body_as_unicode()) 

     item = MyItem() 
     item["firstName"] = jsonresponse["firstName"]    

     return item 

희망하는 데 도움이 : 유일한 차이점은 응답을 구문 분석 json 모듈을 사용한다는 것입니다.

+5

당신은'사용할 수 있습니다 json.loads (response.body_as_unicode())'로드는'str' 또는'unicode' 객체가 아닌 scrapy 응답을 필요로한다. –

+1

여러분, 이제 json 응답을 파싱했습니다. 잠재적으로 json에있는 각 링크를 어떻게 따라갈 수 있습니까? – Cmag

+3

@Cmag'Request'를'return' 또는'yield'해야합니다. 자세한 정보를 보시려면 [here] (http://doc.scrapy.org/en/latest/topics/request-response.html#passing- 추가 데이터 - 콜백 - 기능). – alecxe

0

JSON로드되지 가능한 이유는 전후에 작은 따옴표를 가지고 있다는 것입니다. 이 시도 :

json.loads(response.body_as_unicode().replace("'", '"'))