XPath 轴(Axes)最全实战详解
(看完这篇,你就能用轴写出任何复杂关系定位,再也不怕“找不到父级/兄弟/叔叔”了)
1. 什么是轴?
轴就是“从当前节点出发,往哪个方向走”的指令。
XPath 总共有 13 个轴,日常真正高频使用的只有下面这 8 个(其余 5 个基本没人用)。
| 轴名称 | 中文含义 | 方向说明 | 最高频场景 |
|---|---|---|---|
child:: | 子节点 | 往下走一层(默认轴,可省略) | //div/child::a → //div/a |
descendant:: | 所有后代 | 往下任意层(// 的本质) | //div/descendant::span → //div//span |
descendant-or-self:: | 后代 + 自己 | 包含当前节点 | 常用于 contains(., ‘关键词’) |
parent:: | 直接父节点 | 往上一层 | 爬虫找“价格的父容器”最常用 |
ancestor:: | 所有祖先 | 一直往上到根 | 找最近的某个祖先:ancestor::div[1] |
ancestor-or-self:: | 所有祖先 + 自己 | ||
following-sibling:: | 同层后面的兄弟 | 同一级,排在后面的 | 表格下一行、商品列表下一个商品 |
preceding-sibling:: | 同层前面的兄弟 | 同一级,排在前面的 | 表格上一行、翻页“上一页”按钮 |
following:: | 文档后面所有节点 | 当前节点之后全部(跨层级) | 某个输入框后的第一个按钮 |
preceding:: | 文档前面所有节点 | 当前节点之前全部 | 很少用 |
self:: | 自己 | 当前节点本身 | self::div[@class=’active’] |
attribute:: | 属性节点 | @ 的完整写法 | attribute::id → @id |
namespace:: | 命名空间 | XML 专用,HTML 不用 | 忽略 |
2. 8个高频轴实战写法(直接复制使用)
1. child::(默认可省略)
//ul/li 等价于 //ul/child::li
2. descendant::(// 的完整形式)
//div//span 等价于 //div/descendant::span
3. parent::(找爸爸,最常用!)
//span[text()='价格']/parent::div
//span[text()='价格']/.. ← 简写,很多人更爱用
4. ancestor::(找所有爷爷)
//span[text()='商品标题']/ancestor::div[1] ← 最近的一层 div
//span[text()='商品标题']/ancestor::*[contains(@class,'item')] ← 第一个包含 item 类的祖先
5. following-sibling::(同层后面的兄弟)
//th[text()='价格']/following-sibling::td[1] ← 价格对应的单元格
//div[contains(@class,'current')]/following-sibling::div[1] ← 当前高亮的下一个
6. preceding-sibling::(同层前面的兄弟)
//th[text()='价格']/preceding-sibling::th[1] ← “价格”前一列的表头
//li[contains(@class,'active')]/preceding-sibling::li[1] ← 上一个
7. following::(当前节点之后任意位置的第一个)
//input[@id='kw']/following::input[1] ← 搜索框后面的第一个 input(不管在哪层)
//label[text()='验证码']/following::input[1] ← 验证码输入框(超级稳)
8. self::(判断自己)
//div[self::div[@class='login-box']] ← 就是这个登录框本身
3. 经典实战场景(99%的人都会遇到)
| 场景 | 最稳 XPath(使用轴) |
|---|---|
| 找到“价格”对应的数值 | //span[text()=’价格’]/following-sibling::span |
| 找到商品标题所在的整条商品容器 | //h3[contains(text(),’手机’)]/ancestor::div[contains(@class,’item’)][1] |
| 找到当前页码的下一页按钮 | //li[contains(@class,’current’)]/following-sibling::li[1]/a |
| 找到表格某行“操作”列的删除按钮 | //td[text()=’删除’]/parent::td/preceding-sibling::td[5] |
| 找到登录表单的提交按钮 | //input[@placeholder=’密码’]/ancestor::form//button[@type=’submit’] |
| 找到动态 class 的父容器 | //span[contains(text(),’总计’)]/parent::/parent:: |
| 找到“验证码”输入框 | //label[contains(text(),’验证码’)]/following::input[1] |
4. 轴口诀(背下来直接起飞)
“子 descendant,爸 parent 双点,
同层兄 following-sibling,
跨层后 following 最灵,
祖宗 ancestor 一层层,
自己 self 点点点。”
看完这篇,你已经完全掌握 XPath 轴的精髓!
现在随便给你一段 HTML,你都能 10 秒写出最精准、最稳的定位。
要不要来 10 道轴专项练习题?我出 HTML,你用轴写 XPath,当场验证!