Day 2:定位策略入门

📅 2026/7/8 1:21:15
Day 2:定位策略入门
适用人群已经跑通第一个用例想学会如何精准找到页面元素预计耗时8 分钟目标掌握 3 种定位方式 多元素处理为什么要学定位自动化测试的核心就是让工具找到页面上的元素然后操作它。如果定位方式不对会出现两种报错找不到元素— 超时找到多个— strict mode violation今天就来解决这两个问题。认识 3 种定位方法定位方法适用场景getByText通过按钮、链接的可见文字定位getByLabel通过 label 文字定位表单控件getBylocator通过 CSS / XPath 选择器定位当页面有多个匹配元素时用动作方法处理动作方法作用getByFirstlocator取第一个匹配元素getByLastlocator取最后一个匹配元素getBylocatorNth / getByTextNth取第 N 个匹配元素索引从 0 开始用到的页面今天用到 3 个页面headingsTest.htm— 多个标题元素演示 first/last/nthlabel.htm— 表单标签演示 getByLabeltableTest.htm— 表格数据演示 getByText 获取单元格内容headingsTest 页面 — 7 个标题元素多个重名标签label 页面 — 表单控件与 label 绑定tableTest 页面 — 员工表格单元格有重复值上传 day02_step.xlsx文件包含 3 个用例用例名目标页面练习重点headingTestheadingsTest.htmgetByFirstlocator 处理多标签重名labelTestlabel.htmgetByLabel getBylocatorNth 绕过重复标签tableTesttableTest.htmgetByTextNth getByFirstlocator 处理多匹配单元格headingTest 用例详解页面包含 7 个标题元素h1: Heading A h2: Heading A h3: Heading A h1: Heading B h2: Heading C h3: Heading D h3: Heading D多个元素有相同标签名直接getBylocator h3会报 strict mode匹配到 3 个所以改用getByFirstlocator步骤定位方式定位值动作说明1navigateTo打开 headingsTest.htm2getByFirstlocatorh1click取第 1 个 h1Heading A3getByTextHeading Cclick文字唯一h2不会报错4getByFirstlocatorh3click取第 1 个 h3Heading Afirst 原理page.locator(h3) → 匹配 3 个元素Heading A, Heading D, Heading D page.locator(h3).first() → 只取第 1 个 → 精确 1 个元素 ✓这就是处理多元素页面的标准做法。labelTest 用例详解页面 label.htm 包含表单控件通过 label 文字关联到输入框步骤定位方式定位值动作动作值1navigateTolabel.htm2getBylocatorNthinput[type“textbox”]||0inputhello3getByLabelEmailinputtesttest.com4assertLabel||Label验证页面文字⚠️踩坑记录页面上有两个输入框都关联了Username标签getByLabel Username会报 strict mode。改用getBylocatorNth通过 CSS 定位第 1 个文本框即可绕过。Email 只有一个匹配getByLabel正常使用。tableTest 用例详解页面 tableTest.htm 包含员工表格步骤定位方式定位值动作说明1navigateTotableTest.htm2getByTextNth0-0||0getText获取第 1 个0-0单元格文字3assert0-0||0-0验证内容4getByFirstlocator#CellWithIdclick点击 id 为 CellWithId 的第 1 个元素⚠️踩坑记录表格中有 3 个单元格都显示0-0getByText 0-0报 strict mode。改用getByTextNth 0-0||0取第 1 个。同理多个单元格都有idCellWithId用getByFirstlocator #CellWithId取第 1 个。执行与报告点击执行3 个用例依次运行。每个用例都会打开对应的页面并执行操作。执行完成后查看 HTML 报告通过为绿色失败为黄色。执行结果3 个用例 13 个步骤全部通过绿色动手练习把 getByFirstlocator(“h3”) 改成 getBylocator(“h3”)看会不会报错在 labelTest 中把 getByLabel(“Email”) 改成 getByLabel(“Username”)观察报错在 tableTest 中用 getByText(“Steven”) 定位员工名看能否找到唯一元素下一篇预告Day 3 — 定位策略进阶我们将深入讲解 CSS 选择器和 XPath。