2016-07-05 2 views
0

私はrとrvestが初めてです。私は2日前にこのコードに助けを借りて、すべてのプレイヤーの名前を掻き集め、うまく動作します。今では、 "fetch_current_players"という関数にコードを追加しようとしています。そこでは、そのWebサイトのプレーヤーコードのベクトル(URLから取り除かれたもの)も作成されます。グーグルでグーグル、読んだり、自分自身を教えようとしているYouTubeの動画を見たりして、何か助けていただければ幸いです。ありがとう!"文字列"コードをURLから削り取り、rvestを使ってベクターに挿入する

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) 
})) 

答えて

0

私はこの種のものをシンプルで読みやすく、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)  
} 
+0

ありがとうございました。 – Nitreg

関連する問題