You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R的rvest包抓取Basketball Reference季后赛表格失败求助

解决Basketball Reference季后赛表格抓取问题

问题根源在于Basketball Reference的页面结构:季后赛表格的HTML代码被包裹在HTML注释(<!-- ... -->)中,而rvest的html_nodes默认仅解析常规DOM节点,不会读取注释内的内容,因此直接用XPATH或ID查找会失效。

以下是两种可行的解决方法:

方法一:提取注释内容并转为HTML解析

先抓取页面所有注释节点,筛选出包含季后赛表格的内容,再将其转换为可解析的HTML对象:

library(tidyverse)
library(rvest)

# 读取目标页面
url <- "https://www.basketball-reference.com/players/w/whitede01/gamelog/2023"
page <- read_html(url)

# 提取所有HTML注释节点
comments <- page %>%
  html_nodes(xpath = "//comment()") %>%
  html_text()

# 筛选出包含季后赛表格的注释内容(匹配表格ID)
playoff_comment <- str_subset(comments, "pgl_basic_playoffs") %>%
  first()

# 将注释内容转换为HTML,再提取表格
playoff_table <- read_html(playoff_comment) %>%
  html_node("#pgl_basic_playoffs") %>%
  html_table(fill = TRUE, header = TRUE)

方法二:直接定位目标表格对应的注释

如果明确季后赛表格的ID为pgl_basic_playoffs,可以简化步骤直接提取:

url <- "https://www.basketball-reference.com/players/w/whitede01/gamelog/2023"
page <- read_html(url)

# 提取包含目标表格的注释,转HTML后抓取表格
playoff_table <- page %>%
  html_nodes(xpath = "//comment()[contains(., 'pgl_basic_playoffs')]") %>%
  html_text() %>%
  first() %>%
  read_html() %>%
  html_table(fill = TRUE, header = TRUE) %>%
  .[[1]]

额外优化:清理复合表头

页面表格带有复合表头(第一行是统计分类,第二行是具体字段),可使用janitor包简化表头处理:

library(janitor)
playoff_table_cleaned <- playoff_table %>%
  row_to_names(row_number = 2) %>%
  clean_names()

内容的提问来源于stack exchange,提问作者Alexander Agadjanian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:00:19