使用 rvest 抓取同名表
Scraping similarly named tables using rvest
我正在尝试使用 rvest 从 fbref.com 上的不同页面抓取 table 的数据。我已经能够使用以下方法从一页中抓取数据:
library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)
passStats <- WS %>% rvest::html_nodes(xpath = '//*[(@id = "ks_sched_all")]') %>% rvest::html_table() %>% data.frame()
但是当我尝试使用 for 循环将它应用于多个页面时,我遇到了一个问题,因为并非所有页面都对 table 使用相同的 ID。有些是 "ks_sched_all",但有些是 "ks_sched_(4-digit number)"。有什么方法可以提取页面上的任何 table,其 ID 开头为:"ks_sched_"?
您可以将 table
添加到您的 XPath 表达式和 ()
。代码可以是:
library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)
results=list()
i=1
for (tables in 1:length(html_nodes(x = WS,xpath = "//table[starts-with(@id,'ks_sched_')]"))) {
path=paste0('(//table[starts-with(@id,"ks_sched_")])[',i,']')
results[[i]] <- WS %>% html_nodes(xpath = path) %>% html_table() %>% data.frame()
i=i+1
}
我们使用 for
循环,用 length
获取表的数量,每次用 paste0
生成一个新的 XPath 并将结果存储在 list
.
输出:7 个数据帧的列表
我正在尝试使用 rvest 从 fbref.com 上的不同页面抓取 table 的数据。我已经能够使用以下方法从一页中抓取数据:
library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)
passStats <- WS %>% rvest::html_nodes(xpath = '//*[(@id = "ks_sched_all")]') %>% rvest::html_table() %>% data.frame()
但是当我尝试使用 for 循环将它应用于多个页面时,我遇到了一个问题,因为并非所有页面都对 table 使用相同的 ID。有些是 "ks_sched_all",但有些是 "ks_sched_(4-digit number)"。有什么方法可以提取页面上的任何 table,其 ID 开头为:"ks_sched_"?
您可以将 table
添加到您的 XPath 表达式和 ()
。代码可以是:
library(rvest)
URL <- "https://fbref.com/en/squads/822bd0ba/Liverpool"
WS <- read_html(URL)
results=list()
i=1
for (tables in 1:length(html_nodes(x = WS,xpath = "//table[starts-with(@id,'ks_sched_')]"))) {
path=paste0('(//table[starts-with(@id,"ks_sched_")])[',i,']')
results[[i]] <- WS %>% html_nodes(xpath = path) %>% html_table() %>% data.frame()
i=i+1
}
我们使用 for
循环,用 length
获取表的数量,每次用 paste0
生成一个新的 XPath 并将结果存储在 list
.
输出:7 个数据帧的列表