如何为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
相关产品推荐
相关产品推荐

