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

Selenium无法通过部分CSS选择器定位Angular页面元素问题排查

问题分析与解决方案

核心错误原因

你用的CSS选择器[for$=expense-]逻辑完全错误:

  • $=是CSS选择器的属性值结尾匹配规则,只会选中for属性值以expense-结尾的元素,但你的目标元素for值是expense-1-sum,结尾是sum,完全不匹配,所以找不到元素。

正确的选择器写法

根据你的需求,选择对应匹配规则:

  1. 匹配for属性以expense-开头的元素(最贴合你的场景,目标值expense-1-sum的前缀就是expense-):
    [for^="expense-"]
    
  2. 匹配for属性**任意位置包含expense-**的元素:
    [for*="expense-"]
    

修正后的Kotlin代码

以开头匹配为例:

var x: WebElement = driver.extendedDriver().findElement(By.ByCssSelector("[for^=\"expense-\"]"))

额外注意(Angular页面特有的坑)

Angular页面元素多为动态加载,直接用findElement可能因元素未渲染完成报错,建议改用显式等待确保元素加载完成:

import org.openqa.selenium.support.ui.WebDriverWait
import org.openqa.selenium.support.ui.ExpectedConditions
import java.time.Duration

val wait = WebDriverWait(driver, Duration.ofSeconds(10))
val x: WebElement = wait.until(
    ExpectedConditions.presenceOfElementLocated(By.ByCssSelector("[for^=\"expense-\"]"))
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:09