Web 将 table 抓取到 R 中

Web Scraping a table into R

我是网络抓取的新手,我确信我在这里遗漏了一个非常明显的答案,但是我已经用尽了所有 post 我能找到的关于使用 rvest 的信息,XML 、xml2 等从网络上将 table 读入 R,但我没有成功。

我要抓取的 table 示例可以在这里找到: https://www.eliteprospects.com/iframe_player_stats.php?player=364033

我试过了

EXAMPLE <- read_html("http://www.eliteprospects.com/iframe_player_stats.php? 
player=364033")
EXAMPLE


URL <- 'http://www.eliteprospects.com/iframe_player_stats.php?player=364033'
table <- URL %>%  
read_html %>% 
html_nodes("table") 

但我不确定如何处理这些结果以将它们放入数据框或任何可用的内容中。

您需要提取正确的 html_nodes,然后将它们转换为 data.frame。下面的代码是如何着手做这样的事情的一个例子。我发现 Selector Gadget 对于找到正确的 CSS 选择器非常有用。

library(tidyverse)
library(rvest)

# read the html
html <- read_html('http://www.eliteprospects.com/iframe_player_stats.php?player=364033')

# function to read columns
read_col <- function(x){
  col <- html %>%  
    # CSS nodes to select by using selector gadget
    html_nodes(paste0("td:nth-child(", x, ")")) %>% 
    html_text()
  return(col)
}

# apply the function
col_list <- lapply(c(1:8, 10:15), read_col)

# collapse into matrix
mat <- do.call(cbind, col_list)

# put data into dataframe
df <- data.frame(mat[2:nrow(mat), ] %>% data.frame()) 

# assign names
names(df) <- mat[1, ] 

df