대학원 일기

8장: 웹 스크래핑 코드 본문

School/Data Mining and Statistics

8장: 웹 스크래핑 코드

대학원생(노예) 2023. 10. 16. 01:30
# 8.3 공공데이터포털의 목록 추출(단일 페이지)
# 패키지 설치 및 로딩
install.packages("rvest")
library(rvest)

# 웹문서 읽기
url <- "<https://www.data.go.kr/tcs/dss/selectDataSetList.do>"
html <- read_html(url)
html

# 목록 아이템 추출
title <- html_nodes(html, "#apiDataList .title") %>%
  html_text()
title

# 목록 아이템 설명 추출
desc <- html_nodes(html, "#apiDataList .ellipsis") %>%
  html_text()
desc

# 데이터 정제: 제어문자를 공백으로 대체
title <- gsub("[|\\r|\\n|\\t]", "", title)
title

# 데이터 출력
api <- data.frame(title, desc)
api

# 8.4 네이버 영화리뷰 추출 (단일 페이지)

# 패키지 설치
install.packages("rvest")
library(rvest)

# 웹문서 읽기
url <- "<https://movie.naver.com/movie/point/af/list.nhn>"
html <- read_html(url)
html

# 리뷰 셀 추출 
review_cell <- html_nodes(html, "#old_content table tr .title")
review_cell

# 평점 추출 
score <- html_nodes(review_cell, "em") %>%
  html_text()
score

# 리뷰 추출 
review <- review_cell %>% 
  html_text()
review

# 리뷰 데이터 정제 
# (1) 리뷰 앞 공통부분이 있는 위치
index.start <- regexpr("\\t별점 -", review)
index.start
# (1) 리뷰 뒤 공통부분이 있는 위치
index.end   <- regexpr("\\t신고", review)
index.end
# (2) 리뷰 추출 
review <- substring(review, index.start, index.end)
review
review <- substring(review, 16)
review
# (3) 제어문자 제거(제어문자를 공백으로 대체)
review <- gsub("[|\\n|\\t]", "", review)
review
# (4) 리뷰 좌우 공백 제거
review <- trimws(review, "both")
review

'School > Data Mining and Statistics' 카테고리의 다른 글

10장: Naver OPEN API  (0) 2023.10.16
9장: OPEN API  (0) 2023.10.16
7장: 지도 활용 코드  (0) 2023.10.16
연속 확률 분포  (0) 2023.10.16
이산형 확률 분포  (0) 2023.10.16
Comments