我正在尝试以编程方式从 NBA Reference 中提取给定日期的所有方框分数(我使用的是 2020 年 1 月 4 日,其中有多场比赛)。我首先创建一个整数列表来表示要拉取的框分数数量:
games<- c(1:3)
然后,我使用浏览器中的开发人员工具
来确定每个表包含的内容(您可以使用选择器小工具
):
#content > div.game_summaries > div:nth-child(1) > table.team
然后我使用 purrr::map
创建要拉取的表的列表,使用 games
:
map_list<- map(.x= '', paste, '#content > div.game_summaries > div:nth-child(', games, ') > table.teams',
sep = "")
# check map_list
map_list
然后,我尝试使用 tidyverse
和 rvest
通过 for
循环运行此列表以生成三个表,这产生了错误:
for (i in map_list){
read_html('https://www.basketball-reference.com/boxscores/') %>%
html_node(map_list[[1]][i]) %>%
html_table() %>%
glimpse()
}
Error in selectr::css_to_xpath(css, prefix = ".//") :
Zero length character vector found for the following argument: selector
In addition: Warning message:
In selectr::css_to_xpath(css, prefix = ".//") :
NA values were found in the 'selector' argument, they have been removed
仅供引用,如果我明确表示 html 或调用 map_list
中的确切项目,则代码将按预期工作(运行以下项目以供引用):
read_html('https://www.basketball-reference.com/boxscores/') %>%
html_node('#content > div.game_summaries > div:nth-child(1) > table.teams') %>%
html_table() %>%
glimpse()
read_html('https://www.basketball-reference.com/boxscores/') %>%
html_node(map_list[[1]][1]) %>%
html_table() %>%
glimpse()
如何在列表中实现此功能?我看过other threads但即使他们使用相同的网站,他们也不是同一个问题。
最佳答案
使用您当前的map_list
,如果您想使用for
循环,这就是您应该使用的
library(rvest)
for (i in seq_along(map_list[[1]])){
read_html('https://www.basketball-reference.com/boxscores/') %>%
html_node(map_list[[1]][i]) %>%
html_table() %>%
glimpse()
}
但我认为这更简单,因为您不需要使用 map
来创建 map_list
,因为 paste
已矢量化:
map_list<- paste0('#content > div.game_summaries > div:nth-child(', games, ') > table.teams')
url <- 'https://www.basketball-reference.com/boxscores/'
webpage <- url %>% read_html()
purrr::map(map_list, ~webpage %>% html_node(.x) %>% html_table)
#[[1]]
# X1 X2 X3
#1 Indiana 111 Final
#2 Atlanta 116
#[[2]]
# X1 X2 X3
#1 Toronto 121 Final
#2 Brooklyn 102
#[[3]]
# X1 X2 X3
#1 Boston 111 Final
#2 Chicago 104
关于rvest:for循环/映射使用html_node和html_table拉取多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606010/