본문 바로가기
웹 크롤링/Jupyter Notebook - 크롤링

주피터 - 웹 크롤링 - 네이버 책 검색기

by 빵으니 2020. 6. 15.
NAVER_BOOK

네이버 책 검색기

폰트 조정

In [1]:
%%html
 
<!-- 에디터 폰트를 조정합니다. -->
<style type='text/css'>
.CodeMirror{
    font-size: 14px;
    font-family: consolas;
</style>

library import

In [2]:
# library import
import requests
from bs4 import BeautifulSoup

주소 딕셔너리 형태{key:value}로 변환

In [3]:
# 주소 딕셔너리 형태{key:value}로 변환
url = 'https://book.naver.com/search/search.nhn'
params = {'sm':'sta_hty.book', 'sug':'', 'where':'nexearch', 'query':'bigdata'}

GET 요청

In [4]:
# GET 요청
response = requests.get(url, params=params)
status_code = response.status_code
print(status_code)
if status_code == 200:
    text = response.text
200

BeautifulSoup 객체로 str->obj 변환

In [5]:
# str => BeautifulSoup
soup = BeautifulSoup(text)
# print(text)

책 전체 정보 가져오기 (크롬 개발자 도구)

In [6]:
# class 보단 유일무이한 값인 id로 가져오기
# 세 방법 중 하나 편한거 쓰기

book_all = soup.find(id='searchBiblioList')
# book_all = soup.find(attrs={'id':'searchBiblioList'})
# book_all = soup.select_one('#searchBiblioList')

# print(book_all)
In [7]:
# 책 한 권 정보
find_one = soup.find(class_='thumb_type thumb_type2')
#find_one = soup.find(attrs={'class':'thumb_type thumb_type2'})
############아니니닫find_one = soup.select_one('/thumb_type thumb_type2')

print(find_one)
<div class="thumb_type thumb_type2">
<a class="N=a:bls.thumb,r:1,i:98000001_000000000000000000ECC37F" href="http://book.naver.com/bookdb/book_detail.nhn?bid=15516543" target="_blank">
<img alt="KNIME을 활용한 Big Data분석" onerror="this.src='https://ssl.pstatic.net/static/book/image/noimg3.gif';" src="https://bookthumb-phinf.pstatic.net/cover/155/165/15516543.jpg?type=m1&amp;udate=Wed Jul 01 16:51:42 KST 2020"/><span class="mask"><span class="bg1"></span><span class="bg2"></span></span>
</a>
</div>
In [8]:
# class 하위 정보 li 가져오기

# 책 각각, 전체
book_all_li_all = book_all.select('li')
# print(book_all_li_all)

# 책 한 권
book_all_li_one = book_all.select_one('li')
print(book_all_li_one)
<li style="position:relative;">
<div class="thumb type_search">
<div class="thumb_type thumb_type2">
<a class="N=a:bls.thumb,r:1,i:98000001_000000000000000000ECC37F" href="http://book.naver.com/bookdb/book_detail.nhn?bid=15516543" target="_blank">
<img alt="KNIME을 활용한 Big Data분석" onerror="this.src='https://ssl.pstatic.net/static/book/image/noimg3.gif';" src="https://bookthumb-phinf.pstatic.net/cover/155/165/15516543.jpg?type=m1&amp;udate=Wed Jul 01 16:51:42 KST 2020"/><span class="mask"><span class="bg1"></span><span class="bg2"></span></span>
</a>
</div>
</div>
<dl style="width:654px">
<dt>
<a class="N=a:bls.title,r:1,i:98000001_000000000000000000ECC37F" href="http://book.naver.com/bookdb/book_detail.nhn?bid=15516543" target="_blank">KNIME을 활용한 <strong>Big</strong> <strong>Data</strong>분석</a><span> (Click 하나로 끝내는 데이터 분석 KNIME)</span> </dt>
<dd class="txt_block">
<a class="N=a:bls.author,r:1,i:4570282" href="http://book.naver.com/search/search.nhn?query=%EC%A1%B0%EC%B9%98%EC%84%A0&amp;frameFilterType=1&amp;frameFilterValue=4570282">조치선</a>, <a class="N=a:bls.author,r:1,i:9162" href="http://book.naver.com/search/search.nhn?query=%EC%A0%95%EC%98%81%EC%A7%84&amp;frameFilterType=1&amp;frameFilterValue=9162">정영진</a> 외 5명 저 <span class="bar">|</span> <a class="N=a:bls.publisher,r:1,i:" href="http://book.naver.com/search/search.nhn?filterType=7&amp;query=%EC%97%91%EC%85%88">엑셈</a> <span class="bar">|</span> 2019.09.25</dd>
<dd class="txt_desc">
<div class="review_point">
<span style="width:100.0%;">별점</span>
</div>
				10.0<span class="blind">점</span>
<span class="bar"> | </span>
<a class="N=a:bls.review,r:1,i:" href="/bookdb/review.nhn?bid=15516543">네티즌리뷰</a>
					3건
				<span class="bar">|</span>
<a class="N=a:bls.bookbuy,r:1,i:98000001_000000000000000000ECC37F" href="javascript:showBuyLayerByBid('15516543')" id="buy_btn_15516543" onclick="return showAdultLayer('15516543', 'false', 'false', 'false');"><img alt="도서구매" class="btn v2" height="20" id="btn_buy_img_15516543" src="https://ssl.pstatic.net/static/book/image/btn_book_buy.gif" title="구매 가능한 도서입니다." width="48"/></a>
					 <strike>25000원</strike> → <em class="price">22500원(-10%)</em>
</dd>
<dd id="searchDescrition_15516543" line="3" type="책소개">
<span class="txt_g1">소개 </span>
				쉽고 빠르게 활용할 수 있는 KNIME ANALYTICS PLATFORM 기반 데이터 분석KNIME은 독일의 KONSTANZ 대학에서 개발된 워크플로우 기반의 통합 데이터 분석 플랫폼입니다. ‘KNIME을 활용한 빅데이터 분석’은 데이터 분석을 처음 접하는 학생들과 현업 담당자들을 위하여 집필하였고 데이터 선택...</dd>
<!-- 연관도서 노출 -->
</dl>
</li>
In [9]:
# 책 bid 가져오기
bid_one = book_all_li_one.a['href'].split('=')[1]
# print(bid_one)

# 책 bid 여러개 가져오기
# for book_all_li_one in book_all_li_all:
#     print(book_all_li_one.a['href'].split('=')[1])
    
# 책 bid 여러개 가져와서 list에 담기
bid_list = []
for book_all_li_one in book_all_li_all:
    b_id = book_all_li_one.a['href'].split('=')[1]
    bid_list.append(b_id)
print(bid_list)
['15516543', '13587569', '16384789', '13783099', '16338249', '14594752', '13784550', '13399152', '16327795', '16346530', '10390764', '16276774', '13409559', '15748262', '15746028', '10220466', '15744672', '16113809', '7185569', '15811120']
In [10]:
# 책 제목 하나 가져오기
title_one = book_all_li_one.img['alt']
#print(title_one)

# 책 전체 가져와서 list에 담기
title_list = []
for book_all_li_one in book_all_li_all:
    b_title = book_all_li_one.img['alt']
    title_list.append(b_title)
print(title_list)
['KNIME을 활용한 Big Data분석', '빅데이터', 'Big Data in Astronomy: Scientific Data Processing for Advanced Radio Telescopes', '빅데이터 리더십', 'BIG DATA를 활용한 K-뷰티경영학', '헬스케어.의료분야 인공지능(AI)과 빅데이터(Big Data)의 핵심기술 개발동향과 국내외 시장 분석', '빅데이터 빅마인드', 'Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us about Who We Really Are', 'Knowledge Discovery in Big Data from Astronomy and Earth Observation: Astrogeoinformatics', 'Ocean Energy Modeling and Simulation with Big Data: Computational Intelligence for System Optimizati', 'Big Data', 'Systems Simulation and Modeling for Cloud Computing and Big Data Applications', '지식의 방주039 대한민국 여행트렌드 2018 Ⅹ. 빅데이터(Big Data)', 'Big Data', 'Big Data', 'MY BIG DATA', 'Big Data', 'Sharing Economy and Big Data Analytics', 'Big Data', 'Big Data Mining for Climate Change']

문제 풀기

In [11]:
# 저자 / 출판사 / 출판일 / 가격 정보가져오기
# 저자/출판사/출판일 정보 하나씩 가져오기
book_text = book_all_li_one.select_one('dd.txt_block').text
#print(book_text)
book_text = book_text.replace('\n','').replace('\r','')
book_text = book_text.replace('\t','').replace('\xa0','')
book_text_list = book_text.split('|')
book_author = book_text_list[0]
book_publisher = book_text_list[1]
book_pubdate = book_text_list[2]
print(book_author,book_publisher,book_pubdate)



# publisher = soup.find(class_='txt_block').a.text
# print(publisher)

# publisher_list = []
# for book_all_li_one in book_all_li_all:
#     print(soup.find(class_='txt_block').a.text)
#     publisher = soup.find(class_='txt_block').a.text
#     publisher_list.append(publisher)
#     print(publisher_list)

#pub_date = 

#price = book_all_li_one.select(#'buy_btn_15516543')
#print(price)
Zhihua Zhang 저  Elsevier 2019.12.03
In [12]:
# 저자 전체 정보 불러오기
author_list = list()
publisher_list = list()
pubdate_list = list()

for book_all_li_one in book_all_li_all:
    book_text = book_all_li_one.select_one('dd.txt_block').text
    book_text = book_text.replace('\n','').replace('\r','')
    book_text = book_text.replace('\t','').replace('\xa0','')
    book_text_list = book_text.split('|')
    #print(book_text_list)
    if(len(book_text_list)) == 4:
        book_author = book_text_list[0] + book_text_list[1]
        book_publisher = book_text_list[2]
        book_pubdate = book_text_list[3]
    else:
        book_author = book_text_list[0]
        book_publisher = book_text_list[1]
        book_pubdate = book_text_list[2]
    author_list.append(book_author)
    publisher_list.append(book_publisher)
    pubdate_list.append(book_pubdate)
print(author_list)
print(publisher_list)
print(pubdate_list)   
['조치선, 정영진 외 5명 저 ', '안지선 글  송진욱 그림', 'Linghe Kong 저 ', '김진호(대학교수), 최용주(대학부총장) 저 ', '이범식 김은주 전소현 이상범 저 ', '편집부 저 ', '박형준 저 ', 'Stephens-davidowitz, Seth 저 ', 'Petr Skoda 저 ', 'Vikas Khare 저 ', '버나드 마 저  Ann Lee 역', 'Dinesh Peter 저 ', '조명화(여행작가) 저 ', 'Pedersen, John S. (EDT), Wilkinson, Adrian (EDT) 저 ', 'Sarangi, Saswat, Sharma, Pankaj 저 ', '이랑(가수), 황국영 저 ', 'Sarangi, Saswat, Sharma, Pankaj 저 ', 'Soraya Sedkaoui 저 ', '빅토어 마이어 쇤베르거(대학교수) 저 ', 'Zhihua Zhang 저 ']
['엑셈', '봄볕', 'Elsevier', '북카라반', '구민사', 'IRSGlobal', '리드리드출판', 'DeyStreetBooks', 'Elsevier', 'Elsevier', '교학사', 'Elsevier', '테마여행신문TTNThemeTravelNewsKorea', 'EdwardElgarPub', 'RoutledgeIndia', '소시민워크', 'RoutledgeIndia', 'Wiley-ISTE', 'JohnMurrayPublishers', 'Elsevier']
['2019.09.25', '2018.05.16', '2020.06.26', '2018.07.25', '2020.04.20', '2019.02.26', '2018.07.27', '2018.02.27', '2020.04.22', '2020.04.21', '2016.03.20', '2020.03.09', '2018.03.03', '2019.11.29', '2019.10.05', '2016.02.01', '2019.10.03', '2020.01.09', '2013.03.01', '2019.12.03']
In [13]:
# 책 한 권 가격 정보 가져오기
book_txt_desc = book_all_li_all[1].select_one('dd.txt_desc') # 전체 정보 중에 1index 값 정보 가져오기
#print(book_txt_desc)

price_org = book_txt_desc.select_one('strike').text
#print(price_org)

price_org = price_org.split('원')[0]
print(price_org)

price_disc = book_txt_desc.select_one('em.price').text
#print(price_disc)

price_disc = price_disc.split('원')[0]
print(price_disc)
13000
11700
In [14]:
# 책 정보 모두 가져오기

price_list = list()

for book_all_li_one in book_all_li_all:
    book_txt_desc = book_all_li_one.select_one('dd.txt_desc')
    price_org = book_txt_desc.select_one('strike')
    price_disc = book_txt_desc.select_one('em.price')
    # pirce가 None인 경우 해결하기
    if price_org == None:
        price_org = 0
    else:
        price_org = price_org.text.split('원')[0] # text만 뽑아서 작업
        
    if price_disc == None:
        price_disc = 0
    else:
        price_disc = price_disc.text.split('원')[0]
        
    price_list.append((price_org, price_disc))
    
print(price_list)
[('25000', '22500'), ('13000', '11700'), (0, 0), ('16000', '14400'), ('21000', '20370'), ('390000', '351000'), ('15800', '14220'), ('22220', '13880'), (0, 0), (0, 0), ('14000', '12600'), (0, 0), (0, 0), ('189540', '186800'), ('69100', '56670'), (0, 0), ('196560', '176500'), (0, 0), (0, 0), (0, 0)]
In [15]:
# 최종 총 정보 dict로 뽑아 list에 담아주기

book_info_list = list()

for i in range(len(bid_list)):
    book_info_dict = dict() # 동일한 키 값이 올 수 없으므로 반복할 떄마다 새로운 key값 담아줌
    book_info_dict['bid'] = bid_list[i]
    book_info_dict['title'] = title_list[i]    
    book_info_dict['author'] = author_list[i]
    book_info_dict['publisher'] = publisher_list[i]
    book_info_dict['pubdate'] = pubdate_list[i]
    book_info_dict['price_org_disc'] = price_list[i]
    book_info_list.append(book_info_dict)
print(book_info_list)
[{'bid': '15516543', 'title': 'KNIME을 활용한 Big Data분석', 'author': '조치선, 정영진 외 5명 저 ', 'publisher': '엑셈', 'pubdate': '2019.09.25', 'price_org_disc': ('25000', '22500')}, {'bid': '13587569', 'title': '빅데이터', 'author': '안지선 글  송진욱 그림', 'publisher': '봄볕', 'pubdate': '2018.05.16', 'price_org_disc': ('13000', '11700')}, {'bid': '16384789', 'title': 'Big Data in Astronomy: Scientific Data Processing for Advanced Radio Telescopes', 'author': 'Linghe Kong 저 ', 'publisher': 'Elsevier', 'pubdate': '2020.06.26', 'price_org_disc': (0, 0)}, {'bid': '13783099', 'title': '빅데이터 리더십', 'author': '김진호(대학교수), 최용주(대학부총장) 저 ', 'publisher': '북카라반', 'pubdate': '2018.07.25', 'price_org_disc': ('16000', '14400')}, {'bid': '16338249', 'title': 'BIG DATA를 활용한 K-뷰티경영학', 'author': '이범식 김은주 전소현 이상범 저 ', 'publisher': '구민사', 'pubdate': '2020.04.20', 'price_org_disc': ('21000', '20370')}, {'bid': '14594752', 'title': '헬스케어.의료분야 인공지능(AI)과 빅데이터(Big Data)의 핵심기술 개발동향과 국내외 시장 분석', 'author': '편집부 저 ', 'publisher': 'IRSGlobal', 'pubdate': '2019.02.26', 'price_org_disc': ('390000', '351000')}, {'bid': '13784550', 'title': '빅데이터 빅마인드', 'author': '박형준 저 ', 'publisher': '리드리드출판', 'pubdate': '2018.07.27', 'price_org_disc': ('15800', '14220')}, {'bid': '13399152', 'title': 'Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us about Who We Really Are', 'author': 'Stephens-davidowitz, Seth 저 ', 'publisher': 'DeyStreetBooks', 'pubdate': '2018.02.27', 'price_org_disc': ('22220', '13880')}, {'bid': '16327795', 'title': 'Knowledge Discovery in Big Data from Astronomy and Earth Observation: Astrogeoinformatics', 'author': 'Petr Skoda 저 ', 'publisher': 'Elsevier', 'pubdate': '2020.04.22', 'price_org_disc': (0, 0)}, {'bid': '16346530', 'title': 'Ocean Energy Modeling and Simulation with Big Data: Computational Intelligence for System Optimizati', 'author': 'Vikas Khare 저 ', 'publisher': 'Elsevier', 'pubdate': '2020.04.21', 'price_org_disc': (0, 0)}, {'bid': '10390764', 'title': 'Big Data', 'author': '버나드 마 저  Ann Lee 역', 'publisher': '교학사', 'pubdate': '2016.03.20', 'price_org_disc': ('14000', '12600')}, {'bid': '16276774', 'title': 'Systems Simulation and Modeling for Cloud Computing and Big Data Applications', 'author': 'Dinesh Peter 저 ', 'publisher': 'Elsevier', 'pubdate': '2020.03.09', 'price_org_disc': (0, 0)}, {'bid': '13409559', 'title': '지식의 방주039 대한민국 여행트렌드 2018 Ⅹ. 빅데이터(Big Data)', 'author': '조명화(여행작가) 저 ', 'publisher': '테마여행신문TTNThemeTravelNewsKorea', 'pubdate': '2018.03.03', 'price_org_disc': (0, 0)}, {'bid': '15748262', 'title': 'Big Data', 'author': 'Pedersen, John S. (EDT), Wilkinson, Adrian (EDT) 저 ', 'publisher': 'EdwardElgarPub', 'pubdate': '2019.11.29', 'price_org_disc': ('189540', '186800')}, {'bid': '15746028', 'title': 'Big Data', 'author': 'Sarangi, Saswat, Sharma, Pankaj 저 ', 'publisher': 'RoutledgeIndia', 'pubdate': '2019.10.05', 'price_org_disc': ('69100', '56670')}, {'bid': '10220466', 'title': 'MY BIG DATA', 'author': '이랑(가수), 황국영 저 ', 'publisher': '소시민워크', 'pubdate': '2016.02.01', 'price_org_disc': (0, 0)}, {'bid': '15744672', 'title': 'Big Data', 'author': 'Sarangi, Saswat, Sharma, Pankaj 저 ', 'publisher': 'RoutledgeIndia', 'pubdate': '2019.10.03', 'price_org_disc': ('196560', '176500')}, {'bid': '16113809', 'title': 'Sharing Economy and Big Data Analytics', 'author': 'Soraya Sedkaoui 저 ', 'publisher': 'Wiley-ISTE', 'pubdate': '2020.01.09', 'price_org_disc': (0, 0)}, {'bid': '7185569', 'title': 'Big Data', 'author': '빅토어 마이어 쇤베르거(대학교수) 저 ', 'publisher': 'JohnMurrayPublishers', 'pubdate': '2013.03.01', 'price_org_disc': (0, 0)}, {'bid': '15811120', 'title': 'Big Data Mining for Climate Change', 'author': 'Zhihua Zhang 저 ', 'publisher': 'Elsevier', 'pubdate': '2019.12.03', 'price_org_disc': (0, 0)}]
In [16]:
# 최종 정보에서 원하는 값만 뽑기
print(book_info_list[7]['author'])
print(book_info_list[10]['price_org_disc'])
Stephens-davidowitz, Seth 저 
('14000', '12600')

댓글