R -从不同的维基百科页面抓取一个特定的表



我在试着刮桌子"竞争者"从维基百科(例如https://en.wikipedia.org/wiki/2022_Winter_Olympics)获取过去两届奥运会的每个国家的数据,并将其制作成一个数据框架。我可以得到每个国家的url列表但是,当我开始抓取时,我面临的问题是每个页面都有"竞争对手"表以不同的顺序(有时是第一个,有时是第二个)加上我可以找到一个唯一的标题来标识表(https://en.wikipedia.org/wiki/Spain_at_the_2022_Winter_Olympics)。我试图应用这个代码从维基百科的一个部分刮表,但我不能弄清楚。如有任何帮助,不胜感激。

谢谢!

应该这样做:

library(rvest)
library(dplyr)
h <- read_html("https://en.wikipedia.org/wiki/2022_Winter_Olympics")
links <- h %>% html_elements(css = "#mw-content-text > div.mw-parser-output > table:nth-child(107) > tbody > tr:nth-child(2) > td > div > ul") %>% 
html_elements("li a") %>% 
html_attr("href") 
links <- links[-grep("\#cite", links)]
comps <- list()
for(i in 1:length(links)){
r <- read_html(paste0("https://en.wikipedia.org", links[i]))
ctry <- gsub("/wiki/(.*)_at_the_2022_Winter_Olympics", "\1", links[i])
tabs <- r %>% html_table()
sport <- sapply(tabs, function(x){g <- grep("Sport", colnames(x)); ifelse(length(g) == 0, 0, g)})
ind <- which(sport == 1)
if(str_detect( links[i],"Norway")){
ind <- 7  
}
comps[[i]] <- tabs[[ind]] %>% 
select(Sport, Men, Women, Total) %>% 
mutate(across(c(Men, Women, Total), as.numeric), 
country = ctry)
}
comps <- bind_rows(comps) %>% 
filter(Sport != "Total")

最新更新