-
R로 위키 빌보드 차트 가져오기R 이모저모 2019. 6. 23. 13:55
이번 글에선 R을 이용해서 위키피디아에 있는 빌보드 상위 100곡(year-end hot-100)의 정보와 하이퍼링크를 가져오는 예제 코드를 업로드하겠습니다.
코드는 다음과 같습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#========================================================================== # Topic : Scrapping Music information from wikipedia # # Author : Junmo Nam # Blog : http://apple-rbox.tistory.com #========================================================================== sapply(c('dplyr','XML','rvest'),require,character.only = T) scrap_wiki_billboard = function(year){ #create html object html_obj = paste0("http://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_",year) %>% lapply(read_html) #title and artist, rank wiki_table = html_obj %>% lapply(function(x){(html_nodes(x,'table.wikitable.sortable') %>% html_table %>% as.data.frame)[,-1] %>% mutate(rank = 1:nrow(.))}) %>% bind_rows %>% mutate(Title = gsub('\\"','',Title), year = lapply(year,function(x){rep(x,100)}) %>% unlist) gc() #hyperlinks hplink = lapply(html_obj,function(x){ temp <- (html_nodes(x,'table.wikitable.sortable') %>% html_nodes('tr'))[-1] res = data.frame(song_hplink = '',artists_hplink = '',stringsAsFactors = F)[1:100,] for(i in 1:length(temp)){ link = html_nodes(temp[i],'a') %>% html_attr('href') res[i,1] = link[1] res[i,2] = link[-1] %>% paste(collapse = ' & ') } rownames(res) = NULL return(res) }) total_scraped = bind_cols(wiki_table,hplink %>% bind_rows) return(total_scraped) } #2015 ~ 2018 top 100 billboard res = scrap_wiki_billboard(2015:2018) #summarised by year res %>% group_by(year) %>% summarise(n = n(), singers = n_distinct(Artist.s.), more_exact_singers = n_distinct(artists_hplink)) #summarised by title res %>% group_by(Title) %>% summarise(n = n(), mean_rank = mean(rank)) %>% arrange(desc(n),mean_rank) 사용방법은 함수 scrap_wiki_billboard에 원하는 년도를 숫자 벡터로(예 : 2015:2018) 집어넣으면 되며, 결과는 Title(곡 제목), Artist.s.(가수), rank(해당년도 랭킹), year(년도), song_hplink(곡에 걸려있는 하이퍼링크), artists_hplink(가수에 걸려있는 하이퍼링크, 복수의 가수가 참여한 경우 ' & '으로 합침)의 6개 칼럼으로 이루어진 데이터프레임이 나오게 됩니다.
해당 데이터프레임으로 특정 곡이 해당 기간동안 몇 번 빌보드에 올라왔는지, 가수는 누구인지, 평균 랭킹은 몇이였는지 등을 아래와 같이 확인해 볼 수 있습니다.
연도별 가수의 숫자 곡별 등장횟수와 평균 랭킹 자주 등장했던 상위 10명 아티스트 *가수와 곡의 하이퍼링크를 활용하여 해당 가수/곡에 대한 정보를 더 가져올 수도 있으며, 이에 대해선 따로 글을 써서 다루도록 하겠습니다.
'R 이모저모' 카테고리의 다른 글
R과 Data Wrangling (0) 2019.08.19 웹 크롤링 기초와 R (0) 2019.07.21 ggplot2 : R 시각화 (1) 2019.06.10 R과 네트워크 분석(2) (0) 2019.05.29 R과 네트워크 분석 (1) (0) 2019.05.12