自动化测试 / 系统课时
使用 XPath 定位
使用 XPath 定位
XPath 适合处理仅靠 CSS 难以表达的文本匹配、祖先关系、兄弟关系和复杂层级。写法的重点不是追求路径越长越精确,而是用稳定属性与关系轴缩小范围,并避免把页面绝对层级写死。
学习目标
- 使用相对路径、属性条件和文本条件定位复杂元素。
- 使用
ancestor、following-sibling等轴表达元素关系。 - 避免绝对 XPath、脆弱下标和错误的类名包含判断。
从稳定条件开始
Selenium Python 使用 By.XPATH。通常从 // 开始写相对 XPath,再加属性或文本条件;只有确实需要关系定位时才引入轴。
| 目标 | XPath | 适用情况 |
|---|---|---|
| 属性精确匹配 | //input[@name='email'] |
表单字段 |
| 多条件匹配 | //button[@type='submit' and @data-role='login'] |
目标属性不唯一 |
| 规范化文本 | //button[normalize-space(.)='保存'] |
文本前后可能有空白 |
| 文本包含 | //div[contains(normalize-space(.), '订单已提交')] |
文案有附加内容 |
| 祖先关系 | //button[@data-action='edit']/ancestor::section[1] |
从按钮反查最近容器 |
| 后续兄弟 | //label[normalize-space(.)='邮箱']/following-sibling::input[1] |
标签与输入框并列 |
normalize-space(.) 会合并连续空白并去掉首尾空白,比直接写 text()='保存' 更能适应按钮内部的换行或额外空格。若元素内部还嵌套了 span,. 也比只检查直接文本节点更实用。
用完整页面验证 XPath
下面示例适用于 Selenium 4.6+ Python。脚本创建一个本地页面,并分别演示属性、规范化文本、祖先轴和兄弟轴定位。
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.by import By
html = '''<!doctype html>
<html>
<body>
<section class="order" data-order-id="A1024">
<h2>Order A1024</h2>
<button data-action="edit"><span> Edit </span></button>
</section>
<div class="field-row">
<label>邮箱</label>
<input name="email" value="alice@example.com">
</div>
</body>
</html>'''
page = Path("xpath-demo.html").resolve()
page.write_text(html, encoding="utf-8")
driver = webdriver.Chrome()
try:
driver.get(page.as_uri())
email = driver.find_element(
By.XPATH,
"//input[@name='email']"
)
edit = driver.find_element(
By.XPATH,
"//button[normalize-space(.)='Edit']"
)
order = edit.find_element(
By.XPATH,
"./ancestor::section[1]"
)
sibling_input = driver.find_element(
By.XPATH,
"//label[normalize-space(.)='邮箱']/following-sibling::input[1]"
)
print(email.get_attribute("value"))
print(order.get_attribute("data-order-id"))
print(sibling_input.get_attribute("name"))
finally:
driver.quit()预期输出
alice@example.com
A1024
email./ancestor::section[1] 以当前按钮为上下文向上查找最近的 section;前面的 . 很重要,它让表达式从当前元素开始,而不是重新从整个文档查找。
正确处理 class 与索引
contains(@class, 'card') 可能误匹配 cardinal。如果必须用 XPath 检查类名,可以把 class 前后补空格再判断完整词元。
片段示例(依赖已创建且打开目标页面的 driver):
card = driver.find_element(
By.XPATH,
"//section[contains(concat(' ', normalize-space(@class), ' '), ' card ')]"
)它只在 class 的独立词元中匹配 card;验证时可读取 card.get_attribute("class"),确认结果中确实包含独立的 card 类。
下标也要尽量靠近稳定条件。(//button)[7] 表示页面上的第 7 个按钮,前面新增按钮就会改变结果;//section[@data-order-id='A1024']//button[@data-action='edit'] 则把位置约束替换成业务属性,改版时更不容易漂移。
选择 XPath 还是 CSS
能用稳定 ID、data-* 属性或简单父子关系表达时,CSS 通常更短,也更容易由前端开发共同维护;需要按文本、向上找祖先、按标签寻找相邻控件时,XPath 更直接。
实际项目中可以用一个简单标准检查定位器:是否包含至少一个稳定业务属性,是否避免从 /html/body 开始,是否没有无意义的大下标。满足这三项后,再在 DevTools 的 XPath 搜索中确认只匹配预期元素,最后放入 Selenium 测试。