제작 도전

네이버 금융 크롤링 (주식 테마별 시세)

영성 2021. 5. 12. 14:07
import sys # 시스템
import os  # 시스템

import pandas as pd  # 판다스 : 데이터분석 라이브러리
import numpy as np   # 넘파이 : 숫자, 행렬 데이터 라이브러리
import requests

from selenium import webdriver   # 웹 브라우저 자동화
import time    # 서버와 통신할 때 중간중간 시간 지연. 보통은 1초
#크롬 웹브라우저 실행
driver = webdriver.Chrome("./chromedriver")
url = "https://finance.naver.com/sise/theme.nhn?&page=1"
driver.get(url)
time.sleep(2)
# 해당 html소스에 있는 테이블들을 list안에 있는 dataframe형태로 table 변수에 할당
html = requests.get('https://finance.naver.com/sise/theme.nhn?&page=1') 
table = pd.read_html(html.text)
table[0]

# NaN값 제거
stock = table[0].dropna().reset_index(drop = True)
stock

# 6페이지 for문으로 반복
for i in range(6):
    html = requests.get('https://finance.naver.com/sise/theme.nhn?&page={}'.format(i + 1))
    table = pd.read_html(html.text)
    if i == 0:
        stock = table[0].dropna().reset_index(drop = True)
    else:
        stock1 = table[0].dropna().reset_index(drop = True)
        stock = pd.concat([stock, stock1])

stock = stock.reset_index(drop = True)
stock

# 엑셀로 저장
stock.to_excel('주식테마별시세.xlsx')