programing

스크래피를 사용한 JSON 응답 스크래핑

lovejava 2023. 3. 20. 21:11

스크래피를 사용한 JSON 응답 스크래핑

JSON을 반환하는 웹 요청을 스크래핑하려면 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"
        }
    ]
}

특정 아이템을 스크래치하려고 합니다(예:name그리고.faxcsv에 저장합니다.

스크래피 거 쓰는 거랑 똑같아요.HtmlXPathSelectorhtml 응답에 사용합니다.유일한 차이점은 이 제품을 사용해야 한다는 것입니다.jsonmodule을 사용하여 응답을 해석합니다.

class MySpider(BaseSpider):
    ...


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

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

         return item

사용할 필요가 없다jsonmodule을 지정하여 응답 개체를 해석합니다.

class MySpider(BaseSpider):
...


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

     item = MyItem()
     item["firstName"] = jsonresponse.get("firstName", "")           

     return item

JSON이 로딩되지 않는 이유는 JSON의 앞뒤에 단일 따옴표가 있기 때문일 수 있습니다.이것을 시험해 보세요.

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

언급URL : https://stackoverflow.com/questions/18171835/scraping-a-json-response-with-scrapy