代码之家  ›  专栏  ›  技术社区  ›  K.Hua

当有多个表和特殊性时,在R中刮除html表及其ref链接

  •  0
  • K.Hua  · 技术社区  · 5 年前

    我的问题和这里的问题是一样的: Scraping html table and its href Links in R

    但我的情况下,提供的解决方案不起作用…或者有些事情我不明白。。。 在我的情况下,网页有不止一个表,我不知道如何针对一个特定的表提供的解决方案在另一个问题。。。

    例如在此网页中 https://en.wikipedia.org/wiki/UEFA_Champions_League ,我该如何关注“史上最佳射手”这张桌子?如何获取“玩家”、“国家”和“俱乐部”列的链接?

    我试过类似的

    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") 
    

    但它一直给我其他的联系。

    另外,还有一个困难,就是有些名字是粗体的,有些不是。。。

    1 回复  |  直到 5 年前
        1
  •  0
  •   Ronak Shah    5 年前

    您可以下载页面中的所有表并选择所需的表。

    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 帮助从维基百科检索数据的包。


    为了得到 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." 
    #....