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

如何在Cypress中获取Angular页面ID动态变化元素的当前ID值

解决方案

错误原因分析

  • 第一种写法cy.get('button > span').contains('Click here').find("id")错误:find()方法用于查找DOM子元素,id是元素的属性而非子元素,因此无法通过该方法获取。
  • 第二种写法错误:你定位到的DOM元素是<span>标签,而示例中的id属性挂载在它的父级<button>标签上,对span调用属性获取方法自然拿不到对应id值。

正确实现方式

方式1:定位到span后向上查找父级button,再获取id

// 先定位到包含指定文本的span,再向上找父级button
cy.get('button > span:contains("Click here")')
  .parent('button')
  .invoke('attr', 'id')
  .then(buttonId => {
    // 这里的buttonId就是你需要的动态id值,可以直接在这里使用
    console.log('当前按钮的id是:', buttonId)
    // 后续需要用到这个id的逻辑也写在这里,比如用id定位元素
    cy.get(`#${buttonId}`).click()
  })

方式2:直接定位包含对应文本的button,再获取id

// 直接定位包含"Click here"文本的button元素
cy.get('button:has(span:contains("Click here"))')
  .invoke('attr', 'id')
  .then(buttonId => {
    // 同上面的用法
    cy.log('按钮动态id:', buttonId)
  })

注意事项

Cypress的命令是异步执行的,不要尝试直接将invoke('attr','id')的返回值赋值给变量同步使用,所有依赖该id的逻辑都需要写在then()的回调函数内部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:09:01