前置学习

首先,得对 xpath 语法熟悉哦,可看此链接进行学习
https://www.cnblogs.com/poloyy/p/12626196.html

官方地址

https://github.com/cypress-io/cypress-xpath

安装方式

npm

  1. npm install -D cypress-xpath

Yarn

  1. yarn add cypress-xpath --dev

项目导入插件

在 cypress/support/index.js 文件下写下面语句即可

  1. require('cypress-xpath')

个人总结

调用 xpath() 命令的两种方式

  1. // 直接 cy.
  2. cy.xpath()
  3. // 获取到 element 元素之后再调用
  4. cy.get('ul').xpath()
  5. cy.xpath().xpath()
  6. cy.get('div').first().xpath()

xpath() 命令的返回结果

单个 element 元素或多个 element 元素组成的数组

入门使用的栗子

  1. it('简单的栗子', function () {
  2. cy.xpath('//ul/li')
  3. .should('have.length', 6)
  4. });

调用 Cypress 命令后再接 xpath 命令

  1. it('调用 Cypress 命令后再接 xpath 命令', function () {
  2. cy.xpath('//ul')
  3. .first()
  4. .xpath('./li')
  5. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图1

调用 xpath 后再接一次 xpath 命令

  1. it('调用 xpath 后再接一次 xpath 命令', function () {
  2. cy.xpath('//body/ul')
  3. .xpath('./li')
  4. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图2

根据属性定位元素

  1. it('根据属性定位元素', function () {
  2. cy.xpath('//*[@id="form-wrapper"]')
  3. cy.xpath('//*[@class]')
  4. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图3

选取当前节点的父节点再找元素

  1. it('选取当前节点的父节点', function () {
  2. cy.xpath('//*[@id="form-wrapper"]/../h2')
  3. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图4

根据索引定位

  1. it('根据索引定位', function () {
  2. cy.xpath('//body/ul[1]/li[3]')
  3. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图5

条件表达式

  1. it('条件表达式', function () {
  2. cy.xpath('//*[@name="password" or @id="form-wrapper"]')
  3. }

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图6

模糊匹配函数

  1. it('模糊匹配函数', function () {
  2. cy.xpath('//*[starts-with(@class,"e")]')
  3. cy.xpath('//*[contains(text(),"Show")]')
  4. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图7

定位函数

  1. it('定位函数', function () {
  2. cy.xpath('//input[position()=1]')
  3. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图8

其他定位方式

  1. it('其他定位方式', function () {
  2. cy.xpath('//li[position()=2]/preceding-sibling::li')
  3. // 等价写法
  4. cy.xpath('//li[position()=2]/../li[position()<2]')
  5. });

Cypress系列(98)- cypress-xpath 插件, xpath() 命令详解 - 图9

https://www.cnblogs.com/poloyy/p/14092754.html