Очистка строкового кода от URL и помещение в вектор с помощью rvest в R

Я новичок в r и rvest. Два дня назад мне помогли с этим кодом, который очищает все имена игроков и работает хорошо. Теперь я пытаюсь добавить код в функцию «fetch_current_players», где она также создает вектор кодов игроков для этого веб-сайта (снятый с URL-адреса). Любая помощь будет принята с благодарностью, так как я провел день в гугле, читал и смотрел видео на YouTube, пытаясь научить себя. Спасибо!

library(rvest) 
library(purrr) # flatten/map/safely
library(dplyr) # progress bar

fetch_current_players <- function(letter){

  URL <- sprintf("http://www.baseball-reference.com/players/%s/", letter)
  pg <- read_html(URL)

  if (is.null(pg)) return(NULL)
  player_data <- html_nodes(pg, "b a")
  player_code<-html_attr(html_nodes(pg, "b a"), "href") #I'm trying to scrape the URL as well as the player name
  substring(player_code, 12, 20) #Strips the code out of the URL
  html_text(player_data)
  player_code #Not sure how to create vector of all codes from all 27 webpages
}

pb <- progress_estimated(length(letters))
player_list <- flatten_chr(map(letters, function(x) {
  pb$tick()$print()
  fetch_current_players(x)
}))

person pjlaffey    schedule 05.07.2016    source источник


Ответы (1)


Мне нравится, чтобы такие вещи были простыми и удобочитаемыми, нет ничего плохого в цикле for. Этот код возвращает имена и коды в простом фрейме данных.

library(rvest) 
library(purrr) # flatten/map/safely
library(dplyr) # progress bar

fetch_current_players <- function(letter){
  URL <- sprintf("http://www.baseball-reference.com/players/%s/", letter)
  pg <- read_html(URL)

  if (is.null(pg)) return(NULL)
  player_data <- html_nodes(pg, "b a")
  player_code<-html_attr(html_nodes(pg, "b a"), "href") #I'm trying to scrape the URL as well as the player name
  player_code <- substring(player_code, 12, 20) #Strips the code out of the URL
  player_names <- html_text(player_data)
  return(data.frame(code=player_code,name=player_names))
}

pb <- progress_estimated(length(letters))

for (x in letters) {
  pb$tick()$print()
  if(exists("player_list"))
     {player_list <- rbind(player_list,fetch_current_players(x))
  } else player_list <- fetch_current_players(x)    
}
person PeterK    schedule 05.07.2016