元素定位的常见问题解决方法


  • 动态ID/class

    这种情形下,无法使用传统的定位方式直接定位,但是可以通过其他方式:

    cy.xpath("//*[starts-with(@id,'MultipleTextBox')]")      //找id以MultipleTextBox开头的元素
    cy.xpath("//*[ends-with(@id,'Box')]")   //找id以Box结尾的元素
    cy.xpath("//div[contains(text(),'总计')]"  //找内容中包含“总计”的元素
  • 根据xpath定位到了多个元素,只想获取其中一个
    • 获取的元素后用first(),来获取第一个元素
      1 cy.xpath("//td[text()='order12345678']").first()
    • 如果想要获取第二个或第三个,可以用eq(指定序号),注意序号是从0开始
      //根据xpath可以得到多个元素,eq(1)是获取第二个
      cy.xpath("//*[starts-with(@id,'MultipleTextBox')]").eq(1) 
    • 用last()来获取最后一个元素
      cy.xpath("//*[starts-with(@id,'MultipleTextBox')]").last()

如果确定表达式写的没有问题,就是定位不到,怎么办?

以下均以cypress为例:

  • 增加等待时间

    1 cy.wait(10000)
  • 查看是否在不同的frame中
    cypress如果要使用iframe: 元素被隐藏了 

    • 需要先安装iframe插件
      1 npm install --save-dev cypress-iframe
    •  在cypress\support\commands.js中添加引用
      1 require('cypress-iframe')
    •  在js代码中,按照以下方式调用:
      1 cy.iframe().find('#username').type("test")
  • 最近测试的产品中,要定位左侧菜单的输入框,但是左侧菜单是鼠标移动过去才会显示的,所以用到了trgger模拟鼠标操作

    1 cy.get('#navigator').should('not.be.visible')
    2 cy.xpath('/html/body/div[4]').trigger("mouseover")
    3 cy.get('#navigator')
    4    .should('be.visible')
    
    
    

 

 

相关