XPath starts-with()和ends-with()函数怎么用

37次阅读

starts-with()在XPath 1.0已支持,用于匹配字符串开头;ends-with()仅XPath 2.0+支持,用于匹配结尾;老版本需用subString()+string-Length()模拟,二者均区分大小写且参数自动转字符串。

XPath starts-with()和ends-with()函数怎么用

XPath 的 starts-with()ends-with() 都是用来匹配字符串开头或结尾的函数,但要注意:只有 XPath 2.0 及以上版本才支持 ends-with();而 starts-with() 在 XPath 1.0 就已存在,兼容性更好。

starts-with():判断元素文本或属性是否以指定字符串开头

语法:starts-with(string, substring),返回布尔值(true/false)。常用于定位类名、URL、ID 等有固定前缀的节点。

  • 匹配所有 class 属性以 "btn" 开头的按钮://*[@class and starts-with(@class, "btn")]
  • 查找 href"https://" 开头的链接://a[starts-with(@href, "https://")]
  • 注意:如果属性为空或不存在,starts-with(@attr, "...") 会返回 false,不会报错

ends-with():判断元素文本或属性是否以指定字符串结尾(XPath 2.0+)

语法:ends-with(string, substring),同样返回布尔值。适合筛选文件扩展名、状态后缀等场景。

XPath starts-with()和ends-with()函数怎么用

CodeGeeX

智谱AI发布的AI编程辅助工具插件,可以实现自动代码生成、代码翻译、自动编写注释以及智能问答等功能

XPath starts-with()和ends-with()函数怎么用 191

查看详情 XPath starts-with()和ends-with()函数怎么用

  • 找所有 src".png" 结尾的图片://img[ends-with(@src, ".png")]
  • 选中 class 名以 "-active" 结尾的元素:*[ends-with(@class, "-active")]
  • ⚠️ 如果用在只支持 XPath 1.0 的环境(比如老版本 Selenium 或某些浏览器 DevTools),ends-with() 会直接报错——此时得用替代写法(见下条)

XPath 1.0 中模拟 ends-with() 的方法

因为不支持 ends-with(),可以用 substring() + string-length() 组合实现:

  • 等价于 ends-with(@src, ".pdf") 的写法:@src and substring(@src, string-length(@src) - 3) = ".pdf"
  • 更稳妥一点(避免长度不足报错):@src and substring(@src, string-length(@src) - 3) = ".pdf" and string-length(@src) >= 4
  • 原理:取字符串末尾 4 个字符(”.pdf” 长度为 4),和目标比对

实用小提醒

  • 两个函数都区分大小写,starts-with("apple", "a") 是 false
  • 参数必须是字符串类型,数字或布尔值会自动转字符串(如 starts-with(@id, 123) 等价于 starts-with(@id, "123")
  • 想同时匹配开头和结尾?可以组合使用://a[starts-with(@href,"/page") and ends-with(@href,".html")]

基本上就这些。用对函数能少写很多冗余表达式,特别是处理动态 class 或 URL 时很顺手。

text=ZqhQzanResources