먼저 test data는 다음과 같이 넣어 두었다.
data = [['봉천동','삼우식당'],['신림동','전주식당']]
네이버 API를 신청했을때 받은 아이디와 비밀번호를 저장해 두었다.
client_id = "클라이언트 아이디"
client_secret = "비밀번호"
file_path = "./test.json"
json_data = {}
parsing 방법
search_text = data[0] + ' ' + data[1]
encText = urllib.parse.quote(search_data)
urllib를 이용해 리소스 가져오기
url = "https://openapi.naver.com/v1/search/local.json?query=" + encText
request = urllib.request.Request(url)
request.add_header("X-Naver-Client-Id",client_id)
request.add_header("X-Naver-Client-Secret",client_secret)
response = urllib.request.urlopen(request)
rescode = response.getcode()
성공적으로 리소스를 가져왔다면 아래와 같이 response.read(),response_body.decode('utf-8')메소드를 통해 값을 꺼내올 수 있다
if(rescode==200):
response_body = response.read()
retdata = response_body.decode('utf-8')
jsonResult = json.loads(retdata)
print(retdata)
json_data[search_text] = jsonResult['items']
else:
print("Error Code:" + rescode)
다음은 url 쿼리에 작성할 수 있는 옵션들이다
다음은 검색 API를 사용할 수 있는 URL 종류이다. 나는 이 프로젝트에서 식당 정보를 가져올 것이므로 지역 서비스인 local을 사용하였다
JSON
아래는 크롤링해서 가져온 값을 test.json 파일에 들여쓰기하여 저장하는 코드이다.
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(json_data, file, indent=4)
json파일에 저장된 값을 가져올때는 아래와 같이 하면된다
file_path = "./test.json"
with open(file_path,'r') as file:
test_data = json.load(file)
import os
import sys
import urllib.request
import json
data = [['봉천동','삼우식당'],['신림동','전주식당']]
client_id = "클라이언트 아이디"
client_secret = "비밀번호"
file_path = "./test.json"
json_data = {}
for i in data:
search_text = i[0] + ' ' + i[1]
print(search_text)
encText = urllib.parse.quote(search_text)
url = "https://openapi.naver.com/v1/search/local.json?query=" + encText # json 결과
# url = "https://openapi.naver.com/v1/search/blog.xml?query=" + encText # xml 결과
request = urllib.request.Request(url)
request.add_header("X-Naver-Client-Id",client_id)
request.add_header("X-Naver-Client-Secret",client_secret)
response = urllib.request.urlopen(request)
rescode = response.getcode()
if(rescode==200):
response_body = response.read()
retdata = response_body.decode('utf-8')
jsonResult = json.loads(retdata)
print(retdata)
json_data[search_text] = jsonResult['items']
#build된 시간, display수 등의 정보를 뺀 item안에 내용만 json에 저장하였음
else:
print("Error Code:" + rescode)
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(json_data, file, indent=4)