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

使用R Selenium抓取可折叠表格子表时遇到问题求助

解决R Selenium定位复合类元素错误及抓取子表数据方案

错误原因

你遇到的Compound class names not permitted错误,是因为Selenium的class name定位器不支持空格分隔的复合类名(annotation expand是两个独立的CSS类)。需要改用CSS选择器或XPath来定位同时包含这两个类的元素。

修正后的子表定位代码

替换原错误的定位代码,用以下两种方式之一:

方式1:CSS选择器(推荐)

# 定位所有带annotation和expand类的展开按钮
sub_expand_buttons <- remDr$findElements(using = 'css selector', value = '.annotation.expand')

方式2:XPath

sub_expand_buttons <- remDr$findElements(using = 'xpath', value = "//*[contains(@class, 'annotation') and contains(@class, 'expand')]")

完整子表数据抓取流程

在你现有代码基础上,添加循环展开子表并提取数据的逻辑:

library(tidyverse)
library(RSelenium)
library(rvest)
library(netstat)
library(data.table)

# 初始化驱动
remote_driver <- rsDriver(browser = "chrome", chromever = "126.0.6478.182", verbose = F, port = free_port())
remDr <- remote_driver$client
remDr$open()

# 导航到目标页面
remDr$navigate("https://graphics.axios.com/2019-02-11-harris-polls/index.html?initialWidth=787&childId=av-2019-02-11-harris-polls-N8S34&parentTitle=The%20Axios%20Harris%20Poll%20100%20reputation%20rankings&parentUrl=https%3A%2F%2Fwww.axios.com%2F2019%2F03%2F06%2Faxios-harris-poll-corporate-reputations")

# 展开主表
expand_table <- remDr$findElement(using = 'xpath', '/html/body/div/div[2]/div[1]/span')
expand_table$clickElement()

# 等待主表加载(可选,根据页面速度调整)
Sys.sleep(2)

# 定位所有子表展开按钮
sub_expand_buttons <- remDr$findElements(using = 'css selector', value = '.annotation.expand')

# 初始化存储子表数据的列表
sub_table_list <- list()

# 循环处理每个子表
for (i in seq_along(sub_expand_buttons)) {
  # 点击展开子表(每次重新定位,避免元素状态失效)
  current_button <- remDr$findElements(using = 'css selector', value = '.annotation.expand')[[i]]
  current_button$clickElement()
  
  # 等待子表加载
  Sys.sleep(1)
  
  # 提取当前子表的HTML
  sub_table <- remDr$findElement(using = 'xpath', value = sprintf("//tbody/tr[%d]/td/div/table", i+1)) # 子表在对应行的td内
  sub_table_html <- sub_table$getElementAttribute("outerHTML") %>% unlist()
  sub_page <- read_html(sub_table_html)
  
  # 解析子表为数据框,添加公司标识(比如主表的公司名称)
  sub_df <- html_table(sub_page)[[1]]
  # 可选:从主表获取对应公司名称
  company_name <- remDr$findElement(using = 'xpath', value = sprintf("//tbody/tr[%d]/td[2]", i+1))$getElementText() %>% unlist()
  sub_df$company <- company_name
  
  # 存入列表
  sub_table_list[[i]] <- sub_df
  
  # 关闭子表(可选,避免页面元素重叠)
  current_button$clickElement()
  Sys.sleep(0.5)
}

# 合并所有子表数据
all_sub_data <- bind_rows(sub_table_list)

# 关闭驱动
remDr$close()
remote_driver$server$stop()

注意事项

  • 页面元素的XPath可能需要根据实际结构微调,建议用浏览器开发者工具(F12)确认子表的定位路径。
  • 添加Sys.sleep()是为了等待页面加载,可根据网络速度调整时长。
  • 每次循环重新定位按钮,避免因页面DOM变化导致的元素引用失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:18:27