빅데이터 분석
빅데이터 분석 - 네이버 실시간 검색어 & 코스피 지수 데이터 크롤링
귀건
2020. 10. 2. 05:19
728x90
반응형
과제로 진행한 내용에 대한 소스코드이다. 1번은 어떤 블로그의 예제를 따라서 진행해본 것이고, 2번은 혼자 삽질하면서 진행했다. "LIST" 구조를 만질 때, 자꾸 변환이 안되서 삽질하다가, unlist가 번뜩 생각나서 다 벡터로 바꾸고 하면서 어떻게든 풀었다.(잘풀진 않았다.-_-)
지금은 지치고 피곤한 상태이니, 다음에 짬나면 한번 설명을 업데이트 해보도록 하겠다.
1. 네이버 실시간 검색어
library(rvest)
library(httr)
library(dplyr)
res <- GET(url='https://datalab.naver.com/keyword/realtimeList.naver?where=main')
res
status_code(x=res)
content(x=res, as='text', encoding = 'UTF-8') %>% cat()
html <- read_html(x=res)
span <- html_nodes(x=html, css='span.item_title')
span
searchWords <- html_text(x=span)
print(searchWords)
2. 코스피 지수 데이터
#https://finance.naver.com/sise/sise_index.nhn?code=KOSPI
res <- GET(url = 'https://finance.naver.com/sise/sise_index.nhn?code=KOSPI')
res
status_code(x=res)
content(x=res, as='text',encoding = 'EUC-KR') %>% cat()
html <- read_html(x=res, encoding = 'EUC-KR')
html
span <- html_nodes(x=html,css = '.table_kos_index') %>% html_table()
span #테이블 데이터가 굉장히 꼬여있음.
is.list(span)
#테이블 데이터 전처리
result <- matrix(unlist(span), ncol = 4)
result
is.list(result)
result[1:4,1]
index <- c(result[1:3, 1])
index_data <- c(result[1:3,2])
index2 <- c(result[1:3, 3])
index2_data <- c(result[1:3, 4])
first <- data.frame(index, index_data)
first
second <- data.frame(index2, index2_data)
second
#단어 정리 및 분할.
up_down <- gsub(" ", "", result[4, 2])
up_down
up_down <- gsub("\\n", "", up_down)
up_down <- gsub("종목수" , "종목수:", up_down)
up_down <- strsplit(up_down, "\t")
up_down <- strsplit(unlist(up_down), ":")
up_down
ud_data <- data.frame(unlist(up_down))
ud_data
ud_index <- c(ud_data[c(1,3,5,7,9),1]) # 짝수번쨰가 인덱스
ud_index
ud_data <- c(ud_data[c(2,4,6,8,10),1]) # 홀수번째가 인덱스
ud_data
ud <- data.frame(ud_index, ud_data)
ud
######################################
idx <- c(index, index2, ud_index)
idx
dat <- c(index_data, index2_data, ud_data)
#숫자 데이터로 바꿔주기 위함.
dat <- gsub(",", "", dat)
dat <-as.numeric(dat) #숫자 데이터 변환
dat
# 거래 대금과 거래량 값이 너무 커서 다른 값이 그래프로 나오지 않음. ㅠㅠ 전체 데이터에 대한 막대 그래프
barplot(as.matrix(dat),main="네이버 증권 데이터 시각화", beside=T,axes=F,ylab="",xlab="", las=2,border="white",names.arg=idx)
axis(2)
abline(h=seq(0,35,5),lty=2)
idx_e <- idx[-4]
idx_e <- idx_e[-1]
dat_e <- dat[-4]
dat_e <- dat_e[-1]
#거래 대금과 거래량을 제외한 나머지 값들의 막대 그래프.
barplot(as.matrix(dat_e),main="네이버 증권 데이터 시각화", beside=T,axes=F,ylab="",xlab="", las=2,border="white",names.arg=idx_e)
axis(2)
abline(h=seq(0,35,5),lty=2)
728x90
반응형