소품집

[웹 크롤링] KOSPI 200 기업 본문

Web crawling

[웹 크롤링] KOSPI 200 기업

sodayeong 2020. 4. 25. 16:03

KOSPI 200 종목 부분 추출


네이버 주식에서 코스피 200기업 명과 일별 시세를 뽑아보는 크롤링을 해보려고 합니다.

 

 

코스피 200 기업 추출


# url 요청
res <- GET(url='https://finance.naver.com/sise/entryJongmok.nhn')
print(res)

# 언어방식을 컴퓨터 기본으로 설정
Syslocale(category='LC_ALL', locale='C')

# kospi 200 종목 부분 추출
tbl <- res %>%
  read_html(encoding = 'EUC-KR') %>%
  html_nodes(css='td.ctg a') %>%
  html_text()
print(tbl)

 

상위 200개 종목 링크 가져오기


# 상위 200개 종목 링크 가져오기
# 연동되는 링크 가져오기
temp2 <- res %>%
  read_html(encoding = 'EUC-KR') %>%
  html_nodes(css='td.ctg a') %>%
  html_attr('href')

#완전한 링크 만들기
temp2 <- paste0('https://finance.naver.com',temp2)

  • html_attr('href')는 해당 속성을 가져옴

 

 

항목별 시세 추출 - 일별


# 일별 시세 지출
res <- GET(url='https://finance.naver.com/item/sise_day.nhn?code=005930')
Sys.setlocale(category = "LC_ALL", locale = 'C')

test <- res %>%
  read_html(encoding = 'EUC-KR') %>%
  html_nodes(css='table.type2') %>%
  html_table() # table로 반환 

Sys.setlocale(category = 'LC_ALL', locale = 'korean')
print(test)

 

 

 

페이지 연속 추출


  • 연결 링크 10개까지 가져오기
  • 페이지를 자동으로 넘겨 페이지를 추출하도록!! 
rslt <- list() # 빈 리스트 생성
for (i in 1:10) {
  res <- GET(url='https://finance.naver.com/item/sise_day.nhn?code=005930&',query=list(page=i))
}

Sys.setlocale(category = 'LC_ALL',locale='C') # 로케일 변환

test <- res %>%
  read_html(encoding = 'EUC-KR') %>%
  html_nodes(css='table.type2') %>%
  html_table()
rslt <- append(rslt,test)

 

 

kospi 200 리스트 추출


일자별 시세 추출


페이지가 넘어갈 때 마다 stock이 쌓이게 됩니다.

그래서 url을 가져올 때마다 페이지를 자동으로 넘겨 수집해줄 수 있도록 해봅시다.

stock <- c() # 추출url 생성 
# 상위 편입종목을 추출
for(i in 1:20){stock <- c(stock,
             read_html(paste0("https://finance.naver.com/sise/entryJongmok.nhn?&page=",i),
                       encoding = 'EUC-KR')%>%
               html_nodes(css='td.ctg a') %>%
               html_attr('href'))
}

# 완전한 링크 만들어주기
stock<- paste0('https://finance.naver.com',stock)

앞 finace url을 붙여 full url로 만들어줍니다.

# 시세 탭으로 이용하기 위해 URI를 변경
library(stringr)

# main을 sis_day로 변경되도록!!
stock <- str_replace(stock,'main','sis_day') 

 

 

kospi200, 100일 시세 추출


stock_total <-data.frame()

for (url in stock) {
  Sys.sleep(sample(1,1000,1)) #중간중간에 공백 두기
  stock_sise <-data.frame()
  rslt <-list()
  
  for(i in 1:10){ #종목별로 10페이지만 가져옴
    test <- read_html(paste0(url,"&page=",i),encoding = 'EUC-KR') %>%
      html_nodes(css = 'table.type2') %>%
      html_table()
    rslt <-append(rslt,test) #페이지별로 리스트의 키를 생성해서 데이터 저장
  }
  stock_sise <-do.call(rbind,rslt)
  stock_sise$name <-str_sub(url,nchar(url)-5,nchar(url)) #주식코드를 붙이기 위해서 url에서 추출
  stock_total <-rbind(stock_total,stock_sise)
}

print(stock_totla)
  • 중간중간 슬립을 걸어두는 이유는 웹에서 단기간에 같은 동작을 반복할 경우 IP를 막아 접근하지 못하기 때문에 텀을 두는 것입니다.
  • 하지만 슬립을 걸어두어도 404 error가 나는 경우가 있습니다. 이럴 경우에는 ip를 막아둔 거기 때문에 잠시 쉬었다가 해야합니다.

 

 

데이터 확인


# 빈 행 제거
stock_total <- stock_total[stock_total$날짜!="",]
nrow(stock_total)
head(stock_total)

# 편입항목 확인
table(stock_total$name)

# 변수타입 확인
sapply(stock_total,class)

  • 데이터 변환을 하기 전 타입을 확인합니다.
  • 문자형(character) → 수치형(numeric)으로 변경합시다.
numeric_fn <- function(x){
  x <- as.numeric(gsub(',','',x)) # 수치형으로 변경하는 함수를 생성. ','를 없앰!

final <- cbind(stock_total[1], # 날짜
               as.data.frame(lapply(stock_total[2:7],numeric_fn)), # 나머지는 수치형으로 변경
               stock_total[length(stock_total)]) # 주식 코드명 가져오기
head(final)
sapply(final,class)

날짜를 제외한 컬럼 stock_total[2:7]는 numeric 으로 변한 것을 확인합니다.

 

 

 

변수생성


  • 전일대비 증감 변수 생성
    • 날짜형 인식
library(lubridate)

final$날짜 <- as.Date(final$날짜, format='%Y.%m.%d') # 날짜형으로 인식
final <- final %>% arrange(name, 날짜) # 주식명과 날짜로 정렬

final2 <- final %>% group_by(name) %>%
  do(as.data.frame.integer(sapply(.[2:7],diff))) %>%
  # 그룹별로 함수 적용을 위해 do 사용. 2~7번째 컬럼만 사용하고, 
  #모든 변수에 대해  변수별로 diff 함수 적용
  rbind # 결과를 행으로 합침

 

 

코드 조합 만들기


  • 코드를 추출하고, 두 개씩 쌍을 생성
  • stock_url 에 코드(기업번호)가 있었는데, 이 부분을 추출해 봅시다.
stock_code <- str_sub(stock,nchar(stock)-5,nchar(stock))
stock_comb <- combn(stock_code,2)

stock_code <- str_sub(stock,nchar(stock)-5,nchar(stock))
stock_comb <- combn(stock_code,2) # 조합생성, 조합이 두 줄짜리 메트릭스로 나옴 -> 세로형으로 변경 
class(stock_comb)
stock_comb <- t(stock_comb)

728x90
Comments