starts-with 和 ends-with 是 XPath 字符串匹配函数,分别判断内容是否以指定子串开头或结尾;前者 XPath 1.0 支持,后者需 XPath 2.0+,老版本需用 substring 等替代。

starts-with 和 ends-with 是 XPath 中常用的字符串模糊匹配函数,用来判断属性值或文本是否以指定内容开头或结尾,特别适合处理动态 class、URL、ID 等有规律但不完全固定的场景。
starts-with:匹配开头
语法是 starts-with(string, substring),返回 true 或 false。常用于定位带固定前缀的元素。
- 匹配 class 以 "btn" 开头的按钮:
//*[@class and starts-with(@class, "btn")] - 找 href 以 "https://" 开头的链接:
//a[starts-with(@href, "https://")] - 定位 id 以 "login-" 开头的输入框:
//input[starts-with(@id, "login-")]
注意:如果属性不存在或为空,starts-with(@class, "btn") 会直接返回 false,不会报错;参数自动转为字符串,所以 starts-with(@id, 123) 等价于 starts-with(@id, "123")。
ends-with:匹配结尾(XPath 2.0+)
语法是 ends-with(string, substring),同样返回布尔值。适合筛选文件类型、状态类名等。
- 选 src 以 ".png" 结尾的图片:
//img[ends-with(@src, ".png")] - 找 class 以 "-active" 结尾的元素:
*[ends-with(@class, "-active")] - 同时满足开头和结尾:
//a[starts-with(@href, "/page") and ends-with(@href, ".html")]
⚠️ 如果你用的是老版本 Selenium 或浏览器 DevTools(只支持 XPath 1.0),ends-with() 会报错,得用替代写法:
- 等价于
ends-with(@src, ".pdf")的写法:@src and substring(@src, string-length(@src) - 3) = ".pdf" and string-length(@src) >= 4 - 原理是取末尾 4 个字符比对,加长度判断避免越界错误
常见搭配与实用提醒
这两个函数常和 and、or、contains() 组合使用,提升定位精度。
- 只匹配 class 含 "nav" 且以 "-open" 结尾的菜单项:
//*[@class and contains(@class, "nav") and ends-with(@class, "-open")] - 排除某些情况可配合
not()://button[not(starts-with(@class, "disabled"))] - 大小写敏感:starts-with("Login", "login") 返回 false,必要时统一转小写(需 XPath 2.0+ 的 lower-case())
不复杂但容易忽略细节,用对了能大幅减少冗余表达式和定位失败。










