not()函数用于反转XPath表达式的布尔结果,常用于筛选不满足特定条件的节点。其基本形式为not(expression),可否定属性存在、属性值、文本内容或子元素存在性。常见用法包括//div[not(@class)]选择无class属性的div,//a[not(@target='_blank')]排除target为_blank的链接。误区包括混淆not()作用范围,如not(//div[@class='active'])返回布尔值而非节点集,正确写法应为//div[not(@class='active')]。not()可与and、or结合使用,遵循德摩根定律,如//div[not(@id) and not(@class)]等价于//div[not(@id or @class)]。性能上,not()本身开销小,但内部复杂表达式可能影响效率,建议避免全局搜索,优先在谓词内使用以提高效率。

XPath的
not()
要否定一个XPath表达式,你只需要将该表达式作为
not()
not(expression)
expression
举几个例子,你就能立刻明白它的威力了:
not(true())
false
not(false())
true
class
div
//div[not(@class)]
@class
not()
div
@class
not()
div
<a>
target
_blank
//a[not(@target='_blank')]
target
_blank
<a>
target
<a>
p
//p[not(contains(text(), '重要'))]
span
div
//div[not(./span)]
./span
div
span
not()
and
or
说实话,
not()
基本用法:
正如前面提到的,
not()
[]
//button[not(@disabled)]
//input[not(starts-with(@id, 'temp'))]
//li[not(./a)]
<a>
常见误区:
这里有些坑,我个人就掉过好几次,后来才慢慢琢磨明白:
误区一:对空节点集的理解。 当一个XPath表达式的结果是空节点集时,在布尔上下文中它会被转换为
false
true
//div[not(./span)]
div
span
./span
true
not(true)
false
div
div
span
./span
false
not(false)
true
div
not(//div[@class='active'])
class
active
div
false
true
class
active
div
//div[not(@class='active')]
误区二:not()
not()
//div[not(@class='active')]
class
active
div
not(//div[@class='active'])
class
active
div
误区三:与and
or
not(conditionA and conditionB)
not(conditionA) or not(conditionB)
not(conditionA or conditionB)
not(conditionA) and not(conditionB)
id
class
div
//div[not(@id) and not(@class)]
//div[not(@id or @class)]
这几乎是
not()
选择不包含特定属性的节点:
没有某个特定属性的节点: 如果你想找到页面上所有没有
id
div
//div[not(@id)]
@id
not()
div
@id
not()
div
某个属性的值不符合预期: 假设你有一堆链接,但你只想选择那些
href
#
//a[not(starts-with(@href, '#'))]
img
alt
//img[not(@alt='')]
选择不包含特定子元素的节点:
没有某个直接子元素的节点: 你可能想找到所有没有
<span>
<div>
//div[not(./span)]
./span
div
span
not()
div
没有某个特定类型的后代元素的节点: 如果你想找到所有
<ul>
class
selected
<li>
<ul>
//ul[not(.//li[@class='selected'])]
.//li
ul
li
不包含特定文本内容的节点: 比如你有一堆
div
div
//div[not(contains(text(), '广告'))]
//div[not(contains(text(), '免费') or contains(text(), '优惠'))]
这些都是非常实用的场景,
not()
在更复杂的XPath表达式里,
not()
复杂应用场景:
组合否定条件: 我们经常需要同时满足多个否定条件。比如,我想找一个
div
id
class
hidden
//div[not(@id) and not(@class='hidden')]
//div[not(@id or @class='hidden')]
否定函数结果:
not()
p
//p[not(normalize-space(text()) = '')]
normalize-space()
not()
ul
//ul[not(count(./li) = 5)]
//ul[count(./li) != 5]
not()
结合位置谓词: 比如,选择一个
ul
li
li
//ul/li[not(position() = 1)]
//ul/li[position() > 1]
//ul/li[not(self::li[1])]
性能考量:
说实话,谈性能在XPath层面,很多时候有点“玄学”,因为实际的解析器实现、文档大小、以及你所使用的库或工具的优化程度都会有影响。但总的原则是,让你的表达式越具体越好,减少引擎的遍历范围。
not()
not(//div[@class='active'])
div
not()
div
div
//div[not(@attribute)]
div
not()
not()
not(contains(concat(@id, @name, text()), 'keyword'))
not()
最终,掌握
not()
以上就是XPath的not()函数怎么否定表达式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号