오픈 api / url 여러개 사용 질문드립니다.

조회수 847회
import os
import sys
import urllib.request
import datetime
import time
import json
#from config import *


# [CODE 1]
def get_request_url(url):
    req = urllib.request.Request(url)
    req.add_header("X-Naver-Client-Id", "clien-id")
    req.add_header("X-Naver-Client-Secret", "password)
    try:
        response = urllib.request.urlopen(req)
        if response.getcode() == 200:
            print("[%s] Url Request Success" % datetime.datetime.now())
            return response.read().decode('utf-8')
    except Exception as e:
        print(e)
        print("[%s] Error for URL : %s" % (datetime.datetime.now(), url))
        return None


# [CODE 2]
def getNaverSearchResult(sNode, search_text, page_start, display):
    base = "https://openapi.naver.com/v1/search"
    node = "/%s.json" % sNode
    parameters = "?query=%s&start=%s&display=%s" % (urllib.parse.quote(search_text), page_start, display)
    url = base + node + parameters

    retData = get_request_url(url)

    if (retData == None):
        return None
    else:
        return json.loads(retData)


# [CODE 3]
def getPostData(post, jsonResult):
    title = post['title']
    description = post['description']
    org_link = post['originallink']
    link = post['link']

    pDate = datetime.datetime.strptime(post['pubDate'], '%a, %d %b %Y %H:%M:%S +0900')
    pDate = pDate.strftime('%Y-%m-%d %H:%M:%S')

    jsonResult.append({'title': title, 'description': description,
                       'org_link': org_link, 'link': org_link,
                       'pDate': pDate})
    return


def main():
    jsonResult = []

    # 'news', 'blog', 'cafearticle'
    sNode = 'news'
    search_text = 'keyword'
    display_count = 100

    jsonSearch = getNaverSearchResult(sNode, search_text, 1, display_count)

    while ((jsonSearch != None) and (jsonSearch['display'] != 0)):
        for post in jsonSearch['items']:
            getPostData(post, jsonResult)

        nStart = jsonSearch['start'] + jsonSearch['display']
        jsonSearch = getNaverSearchResult(sNode, search_text, nStart, display_count)

    with open('%s_naver_%s.json' % (search_text, sNode), 'w', encoding='utf8') as outfile:
        retJson = json.dumps(jsonResult,
                             indent=4, sort_keys=True,
                             ensure_ascii=False)
        outfile.write(retJson)

    print('%s_naver_%s.json SAVED' % (search_text, sNode))


if __name__ == '__main__':
    main()

안녕하세요 네이버 오픈api를 이용해서 검색 마인드맵 어플을 만들고 싶어서 고민중인 학생입니다.
위의 코드에서 sNode를 변경하여 url을 바꾸는 것은 가능한대, #으로 되어있는 news, blog, cafearticle의 검색결과를 동시에 출력을 하고 싶은데 혹시 방법이 없을까요?

1 답변

  • 그냥 셋 다 출력되기만 하면 OK일 경우, 얘기는 아주 간단합니다.

    def main() :
        jsonResult = []
        for sNode in ('news', 'blog', 'cafearticle') :
            # main() 안에서 sNode 를 참조하는 나머지 코드 부분 일체를 이 밑으로 옮김
    

    그리고 아마 이건 생각하시는 것과는 거리가 있겠죠.
    정확히 어떤 걸 "동시 출력"이라고 부르고 계신 건지 그 정확한 기술 사양 명세가 있으면 좋을 것 같네요. (ex. 셋 중 하나라도 최근게 있으면 실시간으로 출력하기)

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)