출처 https://expersight.com/open-api-adoption-beneficial-saas-business/
import os
import sys
import urllib.request
import datetime
import time
import json
import pandas as pd
now = datetime.datetime.now()
datas = [] #csv파일을 위한 변수
client_id = '' # 자신의 client_id
client_pw = '' # 자신의 client_secret
#[CODE 1]
def get_RequestUrl(url):
req = urllib.request.Request(url)
req.add_header("X-Naver-Client-Id", client_id)
req.add_header("X-Naver-Client-Secret", client_pw)
try:
response = urllib.request.urlopen(req)
if response.getcode() == 200:
print(f"[{now.strftime('%Y년%m월%d일 %H시%M분%S초')}] Url Request Success")
return response.read().decode('utf-8')
except Exception as e:
# if response.getcode() == 400 and datas:
# return None
print(e)
print(f"[{now.strftime('%Y년%m월%d일 %H시%M분%S초')}] Error for URL : {url}" )
return None
#[CODE 2] 네이버 검색 API
def get_NaverSearch(node, srcText, start, display):
base = "https://openapi.naver.com/v1/search"
node = "/%s.json" % node
parameters = "?query=%s&start=%s&display=%s" % (urllib.parse.quote(srcText), start, display)
url = base + node + parameters
responseDecode = get_RequestUrl(url) #[CODE 1]
if (responseDecode == None):
return None
else:
return json.loads(responseDecode)
#[CODE 3]
def get_PostData(node, post, jsonResult, cnt):
if node == 'book':
data = {'제목':post['title'],
'저자':post['author'],
'출판사':post['publisher'],
'출간일':post['pubdate'],
'링크':post['link'],
'이미지':post['image']}
elif node == 'news':
data = {'제목':post['title'],
'링크':post['originallink'],
'내용':post['description']}
elif node == 'shop':
data = {'제목':post['title'],
'브랜드':post['brand'],
'제조사':post['maker'],
'가격':post['lprice'],
'이미지':post['image']}
jsonResult.append(data)
datas.append(data)
return
#[CODE 0]
def main():
nodeType = '''-----------------------------
네이버 검색 대상입니다.
1.book, 2.news, 3.shop
-----------------------------'''
print(nodeType)
node = input('번호를 선택하세요.')
if node == '1': node = 'book'
elif node == '2': node = 'news'
elif node == '3': node = 'shop'
srcText = input(f'{node} 검색할 검색어를 입력하세요: ')
display, cnt = 100, 0
jsonResult = []
jsonResponse = get_NaverSearch(node, srcText, 1, display) #[CODE 2]
total = jsonResponse['total']
while ((jsonResponse != None) and (jsonResponse['display'] != 0)):
for post in jsonResponse['items']:
cnt += 1
get_PostData(node, post, jsonResult, cnt) #[CODE 3]
start = jsonResponse['start'] + jsonResponse['display']
jsonResponse = get_NaverSearch(node, srcText, start, total)
# print(f'가져올 데이터 : {total} 건')
with open(f'./data/naver_{node}_{srcText}', 'w', encoding='utf8') as outfile:
jsonFile = json.dumps(jsonResult, indent=4, sort_keys=True, ensure_ascii=False)
outfile.write(jsonFile)
print("가져온 데이터 : %d 건" %(cnt))
# csv 파일로 저장하기
file = f'./data/naver_{node}_{srcText}.csv'
df = pd.DataFrame(datas)
df.to_csv(file, index=False, encoding="utf-8-sig")
print(f'./data/naver_{node}_{srcText}.csv SAVED')
return df
#-----------
# 시작
#-----------
df = main()
df
import os
import sys
import urllib.request
import datetime
import json
client_id = '' # 자신의 파파고 NMT API ID
client_pw = '' # 자신의 파파고 NMT API PASSWORD
news = [] #csv파일을 위한 변수
#[CODE 1]
def papago(prompt, lang=1):
encText = urllib.parse.quote(prompt)
if lang == 1 :
data = "source=ko&target=en&text=" + encText
else:
data = "source=en&target=ko&text=" + encText
url = "https://openapi.naver.com/v1/papago/n2mt"
req = urllib.request.Request(url)
req.add_header("X-Naver-Client-Id", client_id)
req.add_header("X-Naver-Client-Secret", client_pw)
try:
response = urllib.request.urlopen(req, data=data.encode("utf-8") )
if response.getcode() == 200:
print(f"[{now.strftime('%Y년%m월%d일 %H시%M분%S초')}] Url Request Success")
responseDecode = response.read().decode('utf-8')
if responseDecode == None:
return None
else:
return json.loads(responseDecode)
except Exception as e:
print(e)
print("[%s] Error for URL : %s" % (datetime.datetime.now(), url))
return None
# 메인
lang= int(input('[선택] 1:한글->영어, 2:영어->한글: '))
txt = '한글' if lang==1 else '영어'
prompt= input(f'[번역] 변환할 문장을 입력하세요[{txt}]')
print(f'# 입력 문자 => {prompt}')
jsonResponse = papago(prompt, lang) # 파파고 번역
jsonResponse
print('-'*50)
print(f"# 번역 결과 => {jsonResponse['message']['result']['translatedText']}")
from IPython.display import Image
Image(url='https://shopping-phinf.pstatic.net/main_3815224/38152244716.20230516165404.jpg')