XPath 常用语法速查表
把 XPath 解析 XML/HTML 最常用的语法整理成速查,写爬虫和配置时对照查。
返回 开发工具基础路径 7
/从根节点选取
//从任意位置选取(递归)
.当前节点
..父节点
/bookstore/book根下 bookstore 的 book 子元素
//book文档中所有 book 元素
book/titlebook 下的 title 子元素
谓词过滤 6
//book[1]第一个 book
//book[last()]最后一个 book
//book[position()<3]前两个 book
//book[@lang="zh"]lang 属性为 zh 的 book
//book[price>35]price 大于 35 的 book
//book[title]含有 title 子元素的 book
轴 Axes 7
ancestor::div所有祖先 div
parent::node()父节点
child::title子节点 title
descendant::p所有后代 p
following-sibling::div之后的兄弟 div
preceding-sibling::h2之前的兄弟 h2
self::a自身(当且仅当是 a 时)
常用函数 8
contains(@class, "active")class 属性包含 active
starts-with(text(), "Hello")文本以 Hello 开头
normalize-space()去除首尾空白并压缩中间空白
string-length(text())文本长度
count(//book)book 元素总数
concat("a", "-", "b")字符串拼接
substring("hello", 1, 3)截取子串
translate("abc", "abc", "ABC")字符替换
通配与运算 6
*匹配任意元素节点
@*匹配任意属性
node()匹配任意类型节点
//a | //ba 和 b 的并集
//div[@id="x" and @class="y"]and 条件
//div[@class="a" or @class="b"]or 条件
💡 提示
- // 比 / 慢很多,大范围文档优先用精确路径。
- contains(@class, "x") 会匹配 "x y" 这种复合 class,比精确匹配更实用。
- XPath 1.0 不支持正则,需要正则匹配得上 XPath 2.0 或用 contains 组合。