XPath函数通过字符串处理、节点筛选和逻辑判断等功能,显著提升路径表达式的灵活性与精准度。典型函数如contains()和starts-with()用于模糊匹配属性值,应对动态class或href;normalize-space()清理文本中的冗余空白,提升数据质量;count()和position()支持列表项的定量分析与索引定位;结合text()、substring-before()、translate()等可精准提取复杂文本中的目标信息,如价格、库存数字;在多语言场景中,通过关键词判断语言类型;面对不规则结构时,利用following-sibling、name()、local-name()实现相对定位与泛化选择,增强选择器的鲁棒性。<p>
<p>XPath函数,说白了,就是你在构建路径表达式时,用来给筛选节点、处理数据加点“魔法”的工具。它能让你在原本只能按层级、按属性找节点的基础上,进行字符串操作、数值计算、布尔逻辑判断,甚至对节点集进行更复杂的处理。在我看来,掌握这些函数,是把XPath从“能用”提升到“好用”的关键一步,尤其是在面对那些结构不那么规整,或者你需要从文本里抠出特定信息的时候。
[]
函数名(参数)
count(node-set)
count(//li)
<li>
position()
//div[position() = 2]
<div>
last()
//p[position() = last()]
<p>
id(string)
id('main-content')main-content
string(object)
string(//h1)
<h1>
concat(string1, string2, ...)
concat('Hello', ' ', 'World')contains(string1, string2)
string1
string2
//a[contains(@href, 'product')]
href
starts-with(string1, string2)
string1
string2
//div[starts-with(@class, 'item-')]
class
<div>
substring(string, start, length)
substring('HelloWorld', 6, 5)string-length(string)
//p[string-length(text()) > 50]
<p>
normalize-space(string)
normalize-space(//div[@class='description']/text())
true
false
not(boolean)
//a[not(@target='_blank')]
target
true()
false()
number(object)
sum(node-set)
floor(number)
ceiling(number)
round(number)
class
div
//div[contains(@class, 'card') and contains(text(), '优惠')]
and
contains()
starts-with()
class
id
item-12345
product-card-abc
item-
product-card-
starts-with(@class, 'item-')
href
category=electronics
contains(@href, 'category=electronics')
normalize-space()
normalize-space(text())
count()
position()
count(//ul/li)
//ul/li[position() < 3]
position()
text()
//div[@class='price']/text()
string(.)
normalize-space(.)
normalize-space()
substring-before()
substring-after()
translate()
substring-before(normalize-space(//div[@class='price']/text()), '起')
translate(substring-before(normalize-space(//div[@class='price']/text()), '起'), '¥', '')
data-src
class
class="product-item large active"
active
//div[contains(@class, 'active')]
active
//div[contains(@class, 'product-item') and contains(@class, 'active')]
href
starts-with()
substring-before()
substring-before(@href, '?')
translate()
translate(., '库存:件', '')
number(translate(., '库存:件', ''))
lang()
//h2[contains(text(), '新闻') or contains(text(), '最新')]
//h2[contains(text(), 'News') or contains(text(), 'Latest')]
lang
matches()
translate()
string-length()
following-sibling::*
preceding-sibling::*
position()
//h2[text()='产品详情']/following-sibling::p[position()=1]
结合
或
:** 有时候,你不知道具体的标签名是什么,或者标签名可能会变(比如从
变成
//*[starts-with(name(), 'h')]
h1
h6
local-name()
//p[string-length(normalize-space(text())) > 0]
<p>
id()
id
id('some-id')以上就是XPath函数如何使用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号