You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Nokogiri添加用于类检查的自定义XPath函数?

给Nokogiri添加自定义XPath类检查函数

实现代码

require 'nokogiri'

# 注册自定义XPath函数
Nokogiri::XML::XPathContext.register_function('has-class') do |node, class_name|
  class_attr = node.attribute('class')&.value || ''
  normalized_class = " #{class_attr.strip} "
  normalized_class.include?(" #{class_name} ")
end

# 使用示例
html = <<~HTML
  <div class="foo bar">Test 1</div>
  <div class="foobar">Test 2</div>
  <div class="bar">Test 3</div>
HTML

doc = Nokogiri::HTML(html)

# 查询包含指定类的元素
target_elements = doc.xpath('//div[has-class(., "foo")]')
target_elements.each { |el| puts el.text } # 输出: Test 1

逻辑说明

这个自定义函数完全实现了你要求的XPath逻辑:

contains(concat(' ',normalize-space(@class),' '), ' #{class_name} ')
  • 先获取节点的class属性值,为空时默认设为空字符串
  • 对类属性值做strip(对应XPath的normalize-space),然后前后添加空格
  • 通过字符串包含检查,确保只匹配完整的类名,避免误匹配类似foobar这种包含目标类名字符串的情况

使用方式

在XPath表达式中调用has-class(., "目标类名"),其中.代表当前节点,第二个参数传入要检查的类名即可。

内容的提问来源于stack exchange,提问作者Luma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:09:28