【发布时间】:2019-05-18 09:17:00
【问题描述】:
我已经成功地抓取了我想要的数据(在 SO 用户的帮助下),但是我错过了每个抓取的表中的数据代表谁的关键。因此,我尝试使用 mutate 添加一个名为 player 的字段,该字段与 player[[j]] 相同,但这不适用于列表。我已经阅读了有关 lapply 的内容并尝试过,但也没有成功。关于如何实现这一点的任何建议?
library(rvest)
library(plyr)
library(dplyr)
library(tidyr)
### get a list of players
page <- (0:18)
urls <- list()
for (i in 1:length(page)) {
url<- paste0("https://www.mlssoccer.com/players?page=",page[i])
urls[[i]] <- url
}
tbl <- list()
j <- 1
for (j in seq_along(urls)) {
tbl[[j]] <- urls[[j]] %>%
read_html() %>%
html_nodes("a.name_link") %>%
html_text()
j <- j+1
if (j == length(urls)) break
}
### join all of the names into one data frame
tbl <- ldply(tbl, data.frame)
player_tb<- as.data.frame(lapply(tbl, tolower))
colnames(player_tb) <- 'name'
player_table<- as.list(gsub(" ", "-", player_tb$name))
colnames(player_table) <- 'player'
#### using a list of players, get the game summary for each regular season game, adding the player name to the table
pages<- list()
for( i in seq_along(player_table)) {
page <- paste0("https://www.mlssoccer.com/players/",player_table[i])
pages[[i]] <- page
}
player_stats <- list()
j <- 1
for (j in seq_along(pages)) {
player_stats[[j]] <- pages[[j]] %>%
read_html() %>%
html_nodes("table") %>%
html_table() %>%
mutate(player = player) ## this is the piece that fails
j <- j+1
if (j == length(pages)) break
}
t <- do.call(rbind, player_stats)
【问题讨论】:
标签: r web-scraping dplyr rvest