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

使用R(rvest)爬取NBA数据时遇Chromote端口及启动错误求助

问题描述

尝试使用旧代码爬取NBA官网球员传球数据(逐日抓取)时,调用read_html_live()出现端口/浏览器启动错误:

url=paste0("https://www.nba.com/stats/players/passing?DateFrom=10%2F22%2F2024&DateTo=10%2F22%2F2024")
a = read_html_live(url)

Error in `with_random_port()`:
! Cannot find an available port. Please try again.
Caused by error in `startup()`:
! Failed to start chrome. Error:

该代码在23-24赛季末可正常运行,24-25赛季开始后失效,虽查到rvest Issue#421称chromote更新已修复此问题,但故障依旧。

解决方案

1. 修复浏览器路径与更新依赖包

  • 检查Edge实际安装路径:64位系统默认路径为C:/Program Files/Microsoft/Edge/Application/msedge.exe,旧代码的x86路径可能指向已卸载的32位版本,导致启动失败。
  • 更新所有相关包并手动指定端口范围:
# 更新依赖包
update.packages(c("rvest", "chromote", "httr"))

# 指定Edge正确路径
Sys.setenv(
  CHROMOTE_CHROME = "C:/Program Files/Microsoft/Edge/Application/msedge.exe"
)

# 手动设置端口范围,避开常用占用端口
Sys.setenv(CHROMOTE_PORT = "9222-9300")

2. 调整read_html_live()启动参数

添加无界面启动参数,避免窗口干扰,同时延长超时时间:

library(chromote)
# 初始化Chrome实例,配置启动参数
chrome <- Chrome$new(
  args = c("--headless=new", "--no-sandbox", "--disable-dev-shm-usage"),
  port = sample(9222:9300, 1),
  timeout = 30000
)

# 使用自定义Chrome会话读取页面
a <- read_html_live(url, session = chrome$new_session())

3. 绕过rvest封装,直接调用chromote

直接使用chromote控制浏览器,提升灵活性与稳定性:

nba = function(x) {
  url=paste0("https://www.nba.com/stats/players/passing?DateFrom=",x,"&DateTo=",x,"&page=all&SeasonType=Regular%20Season")
  
  # 初始化Chrome实例
  chrome <- Chrome$new(
    args = c("--headless=new", "--no-sandbox"),
    port = sample(9222:9300, 1)
  )
  session <- chrome$new_session()
  
  # 导航至目标页面,等待表格加载完成
  session$navigate(url)
  session$wait_for_selector('table[class*="Crom_table"]', timeout = 10000)
  
  # 处理分页逻辑
  if (session$find_element('div[class*="Pagination_pageDropdown"] select')$exists()) {
    session$click('div[class*="Pagination_pageDropdown"] select')
    session$send_keys('ArrowUp')
    session$scroll_into_view('div[class*="FooterLegalSection_legalCopy"]')
    session$wait(3)
  }
  
  # 提取并整理表格数据
  temp = session$find_element('table[class*="Crom_table"]')$get_table() %>%
    setNames(colnames) %>%
    select(-dummy) %>%
    mutate(date = x, .before = 1)
  
  # 清理资源
  session$close()
  chrome$close()
  rm(chrome, session)
  gc()
  return(temp)
}

4. 应对反爬机制

24-25赛季NBA官网可能更新了反爬策略,可添加模拟浏览器的请求头:

chrome <- Chrome$new(
  args = c(
    "--headless=new",
    "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
  )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:21:18