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

使用RSelenium抓取单页面多标签数据遇元素定位错误求助

问题描述

需要抓取页面https://www.sofascore.com/southampton-wolverhampton/dsV中球员统计模块下的Summary、Attack等标签数据,使用RSelenium编写代码时,定位.iiSsIo类元素触发NoSuchElementException错误。

代码示例

rD <- rsDriver(browser="firefox", port=free_port(), chromever = NULL)
remDr <- rD[["client"]]
remDr$open()
url <- "https://www.sofascore.com/southampton-wolverhampton/dsV"

remDr$navigate(url)

remDr$findElement(using = "css",value = ".iiSsIo")

错误信息

Selenium message:Unable to locate element: .iiSsIo
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '4.0.0-alpha-2', revision: 'f148142cf8', time: '2019-07-01T21:30:10'
System info: host: 'DESKTOP-MOGN5AG', ip: '192.168.0.114', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '19.0.2'
Driver info: driver.version: unknown

Error:   Summary: NoSuchElement
     Detail: An element could not be located on the page using the given search parameters.
     class: org.openqa.selenium.NoSuchElementException
     Further Details: run errorDetails method
解决方法

1. 等待页面元素加载完成

页面未完全渲染就执行定位操作是常见原因,用显式等待确保元素出现后再操作:

remDr$navigate(url)
# 最长等待10秒,直到元素出现
remDr$waitForElement(using = "css", value = ".iiSsIo", timeout = 10000)
element <- remDr$findElement(using = "css", value = ".iiSsIo")

应急可使用固定睡眠(不推荐长期用):

remDr$navigate(url)
Sys.sleep(5) # 等待5秒让页面加载
element <- remDr$findElement(using = "css", value = ".iiSsIo")

2. 更换稳定的元素选择器

.iiSsIo属于前端框架动态生成的类名,刷新后可能失效,建议用基于文本或稳定属性的选择器:

  • 定位"Summary"标签的XPath写法:
element <- remDr$findElement(using = "xpath", value = "//*[text()='Summary']")
  • 先定位标签父容器再遍历子元素(需自行确认父容器的稳定选择器):
tab_container <- remDr$findElement(using = "css", value = "div[class*='Tabs']")
tabs <- tab_container$findElements(using = "css", value = "button")

3. 检查是否存在iframe嵌套

如果目标元素在iframe内,需先切换到对应iframe:

# 找到页面中的iframe(根据实际情况修改选择器)
iframe <- remDr$findElement(using = "css", value = "iframe")
remDr$switchToFrame(iframe)

# 执行元素定位操作
element <- remDr$findElement(using = "css", value = ".iiSsIo")

# 操作完成后切回主文档
remDr$switchToDefaultContent()

4. 应对反爬机制

Sofascore可能检测自动化工具,可通过以下方式优化:

  • 启用可视化浏览器(避免无头模式);
  • 模拟页面滚动:
remDr$executeScript("window.scrollTo(0, document.body.scrollHeight);")
  • 设置自定义User-Agent:
firefox_profile <- makeFirefoxProfile(list(general.useragent.override = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"))
rD <- rsDriver(browser="firefox", port=free_port(), chromever = NULL, extraCapabilities = firefox_profile)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:33:11