언어 자료구조 알고리즘/파이썬(Python)

[python] 네이버 도서 검색 API 활용 - Json

언제나휴일 2020. 11. 9. 11:56
반응형

Book.py

Book.py
0.00MB

#Book.py
class Book:
    def __init__(self,title,author,price,content="",publisher="",link="",imglink=""):
        self.title = title
        self.author = author
        self.price = price
        self.content = content
        self.publisher = publisher
        self.link = link
        self.imglink=imglink


NaverBookSearcher.py

NaverBookSearcher.py
0.00MB

 

#NaverBookSearcher.py
import urllib.request
import json
from Book import Book
class NaverBookSearcher:
    @staticmethod
    def MakeBook(jsbook):
        title = jsbook["title"]
        author = jsbook["author"]
        price = jsbook["price"]
        content = jsbook["description"]
        publisher = jsbook["publisher"]
        link = jsbook["link"]
        imglink=jsbook["image"]
        return Book(title,author,price,content,publisher,link,imglink)
    def __init__(self):
        self.client_id ="네이버에서 발급받은 자신의 client id"
        self.client_secret = "네이버에서 발급받은 자신의 client secret"
        self.url = "https://openapi.naver.com/v1/search/book.json"
        self.query=""
        self.query_str=""
    def SetQuery(self,qstr):
        self.query = "query="+urllib.parse.quote(qstr)
        self.query_str = self.url+"?"+self.query
    def Request(self,start,display):
        start_str = "start="+str(start)
        display_str = "display="+str(display)
        fquery_str = self.query_str +"&"+start_str+"&"+display_str
        request = urllib.request.Request(fquery_str)
        request.add_header("X-Naver-Client-Id",self.client_id)
        request.add_header("X-Naver-Client-Secret",self.client_secret)
        response = urllib.request.urlopen(request)
        rescode = response.getcode()
        if rescode != 200:
            return None
        content = response.read()
        data = content.decode('utf-8')
        jdata = json.loads(data)
        total = jdata['total']  
        return jdata['items'],total
    def RequestAll(self):
        redatas=list()
        start = 1
        display=10
        datas,total = self.Request(start,display)
        redatas.extend(datas)
        start = start+display
        while (start<total)and(start<1000):
            datas,total = self.Request(start,display)
            redatas.extend(datas)
            start = start+display
        return redatas

main.py

from NaverBookSearcher import NaverBookSearcher
q = input("질의:")

ns = NaverBookSearcher()
ns.SetQuery(q)
books = ns.RequestAll()
for bookjs in books:
    book = NaverBookSearcher.MakeBook(bookjs)
    print("제목:",book.title)
    print("저자:",book.author)
    print("가격:",book.price)
반응형