오늘은 네이버 api를 배웠다.
https://developers.naver.com/main/ 접속해서 로그인
1. 맨위에 Application -> 애플리케이션 등록
2. 이름은 뭐 아무거나 ,,, 네이버 크롤링? 정도로하면된다.
3. 사용 API는 검색으로 선택
4. 비로그인 오픈API 서비스환경은 WEB으로 설정하고 URL은 http://naver.com으로 설정한다.
5.Client ID 와 Client Secret를 저장해놓는다.
6. 맨위에 Documents -> 검색으로 들어간다.
7. 들어가서 내려보면 Python이 있다. 그걸 긁어와서 그대로 주피터에 붙여넣는다.
import os
import sys
import urllib.request
import json
import re
client_id = "ZfhA97N3n2D26_pj344P"
client_secret = "WjSgWdzg65"
keyword = input('블로그 검색어를 입력해주세요')
encText = urllib.parse.quote(keyword)
tlist = []
llist = []
dlist = []
#1000페이지 검색하기위해서 만들어준다.
for pagenum in range(1,1000,100):
#만약 에러가 발생하면 저장이 안되기때문에 에러난건 제외하고 저장하기 위해서
try:
#문서에 들어가보면 요청변수가 여러개있음 그걸 이용해서 하면된다. 예를 들면 display는 검색결과출력건수를 지정하는데 최대 100이다.
# sort는 정렬옵션인데 sim을 넣으면 유사도순이고 dateㄴ는 날싸순이다.
url = "https://openapi.naver.com/v1/search/blog?query=" + encText +"&display=100&sort=sim&start="+str(pagenum)# json 결과 블로그 1~100 101~200
# 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()
jtemp = response_body.decode('utf-8')
jdata = json.loads(jtemp)
jdata['items']
#여기도 문서에 적혀있다. 출력결과가 어떤 변수로 저장되는지 그거 참고해서하면된다.
#https://developers.naver.com/docs/serviceapi/search/blog/blog.md#%EB%B8%94%EB%A1%9C%EA%B7%B8
#모르겠으면 여기 들어가서 쭉 내려보자...
for temp in jdata['items']:
hangul = re.compile('[^ ㄱ-ㅎ|가-힣]+')
tdata = temp['title']
ldata = temp['link']
ddata = hangul.sub(r'',temp['description'])
tlist.append(tdata)
llist.append(ldata)
dlist.append(ddata)
else:
print("Error Code:" + rescode)
except:
print('Error')
result = []
for temp in range(len(tlist)):
temp1 = []
temp1.append(tlist[temp])
temp1.append(llist[temp])
temp1.append(dlist[temp])
result.append(temp1)
f = open('{0} - 네이버API 블로그검색.csv'.format(keyword) , 'w', encoding='utf-8')
f.write('제목'+',' + '링크' + ',' + '내용' + '\n')
for temp in result:
f.write(temp[0] + ',' + temp[1] + ',' + temp[2] +'\n')
f.close()