当存在多个 table 和特殊性时,在 R 中抓取 html table 及其 href 链接

Scraping html table and its href Links in R when there are more than one table and particularities

我的问题其实和这里问的一样:

但是提供的解决方案对我的情况不起作用......或者有一些我不明白...... 就我而言,该网页有多个 table,我不知道如何使用另一个问题中提供的解决方案来定位特定的 table...

例如在这个网页https://en.wikipedia.org/wiki/UEFA_Champions_League中,我将如何关注table"All time top scorers"?我如何获得 "Player"、"Country" 和 "Club(s)" 列的链接?

我试过

links = read_html("https://en.wikipedia.org/wiki/UEFA_Champions_League") %>% 
  html_nodes(xpath = '//*[@id="mw-content-text"]/div/table[5]')%>% 
  html_nodes(xpath = '//td/a')%>% html_attr("href") 

但它一直给我其他链接。

另外还有一个难点就是这里有些名字是粗体有些不是...

您可以下载页面中显示的所有 table 和您需要的 select。

library(rvest)
url <- 'https://en.wikipedia.org/wiki/UEFA_Champions_League'
all_tables <- url %>%
               read_html() %>%
               html_nodes('table.wikitable') %>%
               html_table(fill = TRUE)

所以在你的情况下,你需要

all_tables[[4]]

#                  Player     Country Goals Apps Ratio     Years ....
#1  1   Cristiano Ronaldo    Portugal   128  168  0.76     2003– ....
#2  2        Lionel Messi   Argentina   114  140  0.81     2005– ....
#3  3                Raúl       Spain    71  142  0.50 1995–2011 ....
#4  4       Karim Benzema      France    64  118  0.54     2006– ....
#5  5  Robert Lewandowski      Poland    63   85  0.74     2011– ....
#6  6 Ruud van Nistelrooy Netherlands    56   73  0.77 1998–2009 ....
#7  7       Thierry Henry      France    50  112  0.45 1997–2010 ....
#8  8  Alfredo Di Stéfano   Argentina    49   58  0.84 1955–1964 ....
#9  9   Andriy Shevchenko     Ukraine    48  100  0.48 1994–2012 ....
#10 9  Zlatan Ibrahimović      Sweden    48  120  0.40 2001–2017 ....

您可能还对 WikipediR 包感兴趣,该包有助于从维基百科检索数据。


要从 table 中获取 href 链接,我们可以这样做

url %>%
  read_html() %>%
  html_nodes('table.wikitable') %>%
  .[[4]] %>%
  html_nodes('a') %>%
  html_attr('href') %>%
  paste0('https://en.wikipedia.org', .)

#[1] "https://en.wikipedia.org/wiki/Cristiano_Ronaldo"       
#[2] "https://en.wikipedia.org/wiki/Portugal"                
#[3] "https://en.wikipedia.org/wiki/Manchester_United_F.C." 
#....