XPath 运算符

XPath 运算符最全实战清单(2025版)

真正高频、真正好用的运算符全在这了,直接背会就能写出“手术刀级”定位!

1. 逻辑运算符(and、or、not)

运算符含义实战例子(超常用)
and并且//input[@type='text' and @name='wd']
or或者//input[@type='submit' or @type='button' or @value='登录']
not()不包含//input[not(@disabled)] → 没被禁用的输入框
//div[not(contains(@class,'hide'))] → 没隐藏的 div

2. 比较运算符(数字、字符串都行)

运算符含义实战例子
=等于@name='username'
!=不等于@type!='hidden'
<小于position()<5 → 前4个
<=小于等于position()<=3
>大于position()>last()-2 → 倒数第1和第2个
>=大于等于

3. 数学运算符(常用于 position 计算)

运算符含义实战例子
+position()+1
-last()-1 → 倒数第二个
*很少用
div除(不能用 /)price * 0.9(XPath 2.0+ 支持)
mod取模position() mod 2 = 1 → 所有奇数位

4. 节点集合运算符(| 并集,大杀器!)

运算符含义实战例子(神级)
|并集(或)//input | //button | //a[contains(@class,'btn')] → 所有可能按钮
//h1 | //h2 | //h3 → 所有标题
(//div[@class='price'] | //span[@class='price']) → 价格可能在 div 也可能在 span

5. 最强组合写法(直接抄)

// 1. 同时满足多个属性
//div[contains(@class,'item') and contains(@class,'active')]

// 2. 或者满足其一
//input[@type='text' or @type='search' or @placeholder]

// 3. 既不是这个也不是那个
//div[not(@class='ad') and not(@id='footer')]

// 4. 第3到第8个商品(包含头尾)
(//div[@class='product'])[position()>=3 and position()<=8]

// 5. 奇数位 or 偶数位
(//li)[position() mod 2 = 1]        → 所有奇数行
(//li)[position() mod 2 = 0]        → 所有偶数行

// 6. 倒数前5个(最常用翻页场景)
(//div[@class='page'])[position() > last()-5]

// 7. 取多个可能的登录按钮(超级稳)
(//button | //input | //a)[contains(.,'登录') or contains(.,'Login') or @type='submit'][1]

// 8. 价格不是空的(常用去广告)
(//span[@class='price'])[. != '' and . != '暂无报价']

6. 运算符优先级(记住这点就不写错)

优先级从高到低:

  1. [] 谓词
  2. ///
  3. *divmod
  4. +-
  5. =!=<<=>>=
  6. not()
  7. and
  8. or| ← 优先级最低!

示例(容易出错的):

//div[@class='item' or @class='product'] and contains(@id,'2024')]
// 上面等于:(div[@class='item' or @class='product']) and contains(@id,'2024')

// 如果你想写 class=item 或 class=product 并且 id 含 2024,就要加括号:
//div[(@class='item' or @class='product') and contains(@id,'2024')]

一句话总结

学会 andornot()|position() + 数学运算,你就拥有了 XPath 的“逻辑引擎”。

现在你已经彻底掌握 XPath 所有运算符了!
来试试这道终极题(京东/淘宝都用得上):

需求:找到所有标有“促销”“限时”“秒杀”任意一个标签,并且价格小于1000元的商品容器
你能用一行 XPath 写出来吗?(答案我下一条直接给你)
敢不敢现在就试试?我等着看你的神级写法!

文章已创建 2783

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部