본문 바로가기
R

R 언어 - 이미지 크롤링

by 무지성개발자 2021. 8. 7.

# 크롤링 하고 싶은 웹페이지에 들어가겠습니다.

# 저는 다음에서 '오마이걸'을 검색하고 이미지에 들어갔습니다.

 

# 위 주소를 보면 

'https://search.daum.net/search?w=img&nil_search=btn&DA=NTB&enc=utf8&q=오마이걸' 로 표시되었습니다.

# 뒤에 '오마이걸' 키워드를 'IU'로 바꾸면 'IU'님의 사진이 나옵니다.

 

# 먼저 stringr와 rvest를 준비합니다.

library(stringr)
library(rvest)

 

# 키워들를 제외한 url 변수를 만들어 줍니다.

url = 'https://search.daum.net/search?w=img&nil_search=btn&DA=NTB&enc=utf8&q='

 

# 키워드를 넣고 이를 컴퓨터가 인식할 수 있도록 url 코드로 바꿔주는 작업이 필요합니다.

keyword <- '오마이걸'
keyword <- URLencode(keyword)

 

# 다음 공백없이 url과 키워드를 연결해주는 작업입니다.

url <- paste0(url,keyword) 

 

# 만든 url을 html이 읽을 수 있도록 바꾸어줍니다.

html <- read_html(url)

 

# 다음 이미지의 경우 <div id="imgColl" class="type_partial type_max"> 에 전체 이미지들이 다 들어있습니다.

# 따라서 html에 있는 id imgColl 을 사용하겠습니다.

img_node <- html_nodes(html,'#imgColl')

 

img_mat <- str_match_all(img_node, 'oimgurl: "(.+?)"')[[1]][,2]

 

# 반복문을 통해 파일명이 1.jpg 로 시작하도록 만들었습니다.

# 그리고 download.file을 통해 파일을 pc에 다운받습니다.

index <- 1

for(urls in img_mat){
  download.file(urls, destfile = paste0("image", index, '.jpg'), method = 'curl')
  index = index + 1
}


다운받은 파일의 경로가 궁금하면 실행창에 getwd()를 실행하면 됩니다.

파일 경로 변경시 setwd('경로')로 설정합니다.


함수로 만들기


search_d <- function(){
  library(stringr)
  library(rvest)
  keyword <- scan(what = "")
  keyword <- readline("키워드를 입력하세요 >> ")
  url = 'https://search.daum.net/search?w=img&nil_search=btn&DA=NTB&enc=utf8&q='
  keyword <- URLencode(keyword)
  url <- paste0(url,keyword)
  html <- read_html(url)
  img_node <- html_nodes(html,'#imgColl')
  img_mat <- str_match_all(img_node, 'oimgurl: "(.+?)"')[[1]][,2]
  index <- 1
  for(urls in img_mat){
    download.file(urls, destfile = paste0("image", index, '.jpg'), method = 'curl')
    index = index + 1
  }
}

search_d()