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

网页抓取求助:rvest提取<span>文本失败+RSelenium连接Chrome报错

解决SPA页面数据抓取问题

问题根源

目标页面是单页应用(SPA),rvest直接请求URL只能拿到静态框架HTML,实际表格数据由JavaScript动态加载,因此直接用html_node/html_element无法获取内容;RSelenium报错则是ChromeDriver配置错误+变量名笔误导致。


方案1:修复RSelenium并抓取动态内容

解决连接失败问题

报错核心原因:ChromeDriver版本与本地Chrome不匹配,或未正确配置路径,加上代码中变量名写错。

  1. 查看本地Chrome版本(设置→关于Chrome),下载对应版本的ChromeDriver,放入系统PATH目录,或在代码中指定路径。
  2. 修正后完整代码:
library(rvest)
library(RSelenium)
library(tidyverse)

# 初始化驱动(指定Chrome版本,启用无头模式)
rd <- rsDriver(
  browser = "chrome",
  chromever = "你的Chrome对应版本号", # 示例:"118.0.5993.70"
  extraCapabilities = list(chromeOptions = list(args = c("--headless=new")))
)
remDr <- rd[["client"]] # 注意:原代码中变量名写成了rD,此处修正为rd

# 访问页面并等待JS渲染
remDr$navigate("https://carto.viaseva.org/public/viaseva/building/#/panel/building/b/building_id/3514C")
Sys.sleep(5) # 给页面足够加载时间

# 获取渲染后的完整页面源码
page_source <- remDr$getPageSource()[[1]]
p <- read_html(page_source)

# 提取「Performance environnementales」表格
perf_table <- p %>% 
  html_element(xpath = "//h4[text()='Performance environnementales']/following-sibling::div[contains(@class, 'list-container')]") %>%
  html_elements("li") %>%
  map_dfr(function(item) {
    tibble(
      指标 = item %>% html_element(".text-left") %>% html_text(trim = TRUE),
      值 = item %>% html_element(".text-right") %>% html_text(trim = TRUE)
    )
  })

# 提取「Caractéristiques techniques」表格
tech_table <- p %>% 
  html_element(xpath = "//h4[text()='Caractéristiques techniques']/following-sibling::div[contains(@class, 'list-container')]") %>%
  html_elements("li") %>%
  map_dfr(function(item) {
    tibble(
      指标 = item %>% html_element(".text-left") %>% html_text(trim = TRUE),
      值 = item %>% html_element(".text-right") %>% html_text(trim = TRUE)
    )
  })

# 关闭资源
remDr$close()
rd$server$stop()

# 查看结果
print(perf_table)
print(tech_table)

方案2:直接调用API(更高效稳定)

SPA的动态数据通常来自后端API,通过浏览器开发者工具(F12→网络→XHR)可找到数据接口,直接请求即可绕过JS渲染步骤:

library(httr)
library(jsonlite)
library(tidyverse)

# 请求目标建筑的API接口
response <- GET("https://carto.viaseva.org/public/viaseva/building/api/building/3514C?lang=fr")
raw_data <- fromJSON(content(response, "text"))

# 提取环境性能数据
perf_data <- raw_data$building$environmental_performance %>%
  as_tibble() %>%
  rename(指标 = name, 值 = value)

# 提取技术特征数据
tech_data <- raw_data$building$technical_characteristics %>%
  as_tibble() %>%
  rename(指标 = name, 值 = value)

# 查看结果
print(perf_data)
print(tech_data)

原方法失败的原因

  1. rvest直接请求URL:仅能获取服务器返回的静态HTML框架,表格数据是浏览器加载JS后动态生成的,静态HTML中不存在这些元素,因此html_node/html_element返回空。
  2. RSelenium报错:一是变量名笔误(rD应为rd),二是ChromeDriver与本地Chrome版本不匹配,导致连接被拒绝。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:04:57