스크래피를 사용한 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
그리고.fax
csv에 저장합니다.
스크래피 거 쓰는 거랑 똑같아요.HtmlXPathSelector
html 응답에 사용합니다.유일한 차이점은 이 제품을 사용해야 한다는 것입니다.json
module을 사용하여 응답을 해석합니다.
class MySpider(BaseSpider):
...
def parse(self, response):
jsonresponse = json.loads(response.text)
item = MyItem()
item["firstName"] = jsonresponse["firstName"]
return item
사용할 필요가 없다json
module을 지정하여 응답 개체를 해석합니다.
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
'programing' 카테고리의 다른 글
"string"을 "time zone 없는 타임 스탬프"로 변환하는 방법 (0) | 2023.03.20 |
---|---|
메인 스레드의 동기 XMLHttpRequest는 더 이상 사용되지 않습니다. (0) | 2023.03.20 |
Backbone.js - Backbone에 전체 컬렉션을 저장하는 방법.sync 또는 jQuery.ajax? (0) | 2023.03.20 |
변수가 null인 경우 표시/숨기는 방법 (0) | 2023.03.20 |
성공/오류/최종/각도로 약속 사용JS (0) | 2023.03.15 |