【问题标题】:Remove multiple header rows from table with Rvest in R使用 R 中的 Rvest 从表中删除多个标题行
【发布时间】:2021-03-14 01:46:43
【问题描述】:

我正在尝试从 Sports Reference 中抓取表格:

cu_url <- "https://www.sports-reference.com/cbb/schools/creighton/"

我能够像这样将表格放入数据框中:

cu_html <- read_html(cu_url)
cu_table <- html_nodes(cu_html, "table")
cu_info <- data.frame(html_table(cu_table))
colnames(cu_info) <- cu_info[1,]
cu_info <- cu_info[-1,]

但是,我注意到标题行在整个数据中重复出现。例如,第 22 行再次将标题显示为一行。有没有有效的方法来消除这些?在 HTML 中,标题行都有一个 table row () 类的“thead”,所以我想知道是否可以要求 rvest 忽略这些但我在尝试使用时失败了! =。

欣赏任何想法。如果我需要删除实际的标题才能使其正常工作,我会但更愿意保留该标题并删除重复项。

【问题讨论】:

    标签: r web-scraping dplyr rvest


    【解决方案1】:

    您只能保留Rk 列中只有数字的行。

    library(rvest)
    library(dplyr)
    
    cu_url %>%
      read_html %>%
      html_nodes('table') %>%
      html_table() %>%
      .[[1]]  %>%
      setNames(make.unique(unlist(.[1,]))) %>%
      slice(-1L) %>%
      filter(grepl('^\\d+$', Rk)) -> result
    
    result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      相关资源
      最近更新 更多