【问题标题】:Extracting data from scrolling table using Rvest使用 Rvest 从滚动表中提取数据
【发布时间】:2020-07-27 07:18:57
【问题描述】:

我希望从位于https://thearcfooty.com/2017/01/28/a-complete-history-of-the-afl/ 的表中提取所有记录

我面临的挑战是它是一个滚动表格(表格底部的文本显示它包含 31,228 条记录:

Showing 1 to 10 of 31,228 entries

我是 Rvest 的新手,在 Google Chrome 中检查了表格后尝试了以下操作:

library(rvest)
url <- "https://thearcfooty.com/2017/01/28/a-complete-history-of-the-afl/"

Table  <- url %>%
  read_html() %>%
  html_nodes(xpath= '//*[@id="table_1"]') %>%
  html_table()
TableNew <- Table[[1]]
TableNew 

但它只是不断挂起。理想情况下,我想返回一个包含所有行和所有列的所有记录的数据框。

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:

    我的猜测是html_table 中的一些代码有点慢,这就是为什么它会无休止地运行。实际上,您可以阅读所有文本并转换为数据框形状。我没有检查结果是否正确。但根据我观察的几个例子,应该没问题。

    library(rvest)
    #> Loading required package: xml2
    library(data.table)
    url <- "https://thearcfooty.com/2017/01/28/a-complete-history-of-the-afl/"
    
    page <- read_html(url)
    
    tb_str <- page %>% 
      html_nodes(css = 'tr') %>% 
      html_text()
    
    dt <- data.table(raw=tb_str)
    
    headers <- strsplit(tb_str[1],split = "\\W+")[[1]]
    dt[,(headers):=tstrsplit(raw,split="\n +")]
    dt[,raw:=NULL]
    str(dt[!is.na(season)])
    #> Classes 'data.table' and 'data.frame':   31228 obs. of  14 variables:
    #>  $ date             : chr  "08/05/1897" "08/05/1897" "08/05/1897" "08/05/1897" ...
    #>  $ season           : chr  "1897" "1897" "1897" "1897" ...
    #>  $ round            : chr  "1" "1" "1" "1" ...
    #>  $ home_away        : chr  "A" "A" "A" "A" ...
    #>  $ team             : chr  "CA" "SK" "ME" "ES" ...
    #>  $ opponent         : chr  "FI" "CW" "SY" "GE" ...
    #>  $ margin_pred      : chr  "0.00" "0.00" "0.00" "-2.99" ...
    #>  $ margin_actual    : chr  "-33.00" "-25.00" "17.00" "23.00" ...
    #>  $ win_prob         : chr  "0.50" "0.50" "0.50" "0.47" ...
    #>  $ result           : chr  "0.18" "0.24" "0.69" "0.74" ...
    #>  $ team_elo_pre     : chr  "1500" "1500" "1500" "1500" ...
    #>  $ opponent_elo_pre : chr  "1500" "1500" "1500" "1500" ...
    #>  $ team_elo_post    : chr  "1473" "1478" "1515" "1522" ...
    #>  $ opponent_elo_post: chr  "1526" "1521" "1484" "1477" ...
    #>  - attr(*, ".internal.selfref")=<externalptr>
    

    reprex package (v0.3.0) 于 2020-07-27 创建

    【讨论】:

    • 接受这个答案,因为它对解决我的问题最有帮助。
    猜你喜欢
    • 2018-11-03
    • 2020-08-30
    • 2023-03-16
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2021-12-26
    • 2019-12-08
    • 1970-01-01
    相关资源
    最近更新 更多