실시간 Naver 검색어 순위 크롤링 프로그램

최기환·2020년 3월 11일
1

Python

목록 보기
1/2

#1. Code

from selenium import webdriver
from bs4 import BeautifulSoup
from datetime import datetime
import threading

end = False

driver = webdriver.Chrome('/Users/choigihwan/Downloads/coding/python/chromedriver')
driver.implicitly_wait(3)
driver.get('https://datalab.naver.com/keyword/realtimeList.naver?where=main')
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

def crawling(second = 1.0):
    global end
    if end:
        return
    f = open('네이버검색어순위.md', 'a')
    f.write(datetime.today().strftime('\n'+"______________"+'\n'+"%Y/%m/%d %H:%M:%S")+'\n')
    i = 1
    for anchor in soup.select("span.item_title"):
        data = str(i) + "위: "+ anchor.get_text() + '\n'
        f.write(data)
        i += 1
    f.close()
    threading.Timer(second, crawling, [second]).start()

crawling(900)

#2 준비 및 참고

python2는 곧 운명을 다하며, 필자는 python3를 사용해 왔기에
python3 사용자는 pip3를 통해 install 한다.

pip3 install BeautifulSoup
pip3 install selenium

코드와 설명에 관해서는 아래 두 사이트를 참고했다.

https://beomi.github.io/2017/02/27/HowToMakeWebCrawler-With-Selenium/
https://en.wikipedia.org/wiki/Beautiful_Soup_(HTML_parser)

#3 마지막 조언
만들기 정말 정말 정말 쉽다.
라이브러리도 너무 쉽게 잘 정리되어 있다.
여덟 번째 줄에

driver = webdriver.Chrome('/Users/choigihwan/Downloads/coding/python/chromedriver')

이 부분만 본인이 받은 chromedriver 위치로 잘 맞춰주면 끝일 것이다.

위 프로그램의 경우,
프로그램을 시작한 후 15분에 1 번씩 네이버 검색어 순위를 크롤링하여 파일에 누적하여 저장하는 프로그램이다.
(프로그램을 종료하지 않는 이상)

간단한 테스트 프로그램인데, 기본적인 크롤링 프로그램은 물론 주기적으로 데이터를 확인하여 크롤링하는 프로그램에도 적합하다.

profile
개발자를 위한 개발자입니다.

0개의 댓글