【问题标题】:Embed Ruby in xpath/Nokogiri在 xpath/Nokogiri 中嵌入 Ruby
【发布时间】:2013-02-07 03:34:14
【问题描述】:

可能是一个非常简单的问题:

我正在使用 Mechanize、Nokogori 和 Xpath 来解析一些 html:

category = a.page.at("//li//a[text()='Test']")

现在,我希望我在 text()= 中搜索的术语是动态的...即我想创建一个局部变量:

term = 'Test'

如果有意义的话,将本地 ruby​​ 变量嵌入到 Xpath 中。

有什么想法吗?

我的直觉是将其视为字符串连接,但这并不奏效:

term = 'Test'
category = a.page.at("//li//a[text()=" + term + "]")

【问题讨论】:

    标签: ruby xpath nokogiri mechanize


    【解决方案1】:

    当您使用category = a.page.at("//li//a[text()=" + term + "]") 时。方法的最终结果是//li//a[text()=Test],其中 test 不在引号中。因此,要在字符串周围加上引号,您需要使用转义字符 \

       term = 'Test'
       category = a.page.at("//li//a[text()=\"#{term}\"]")
    

       category = a.page.at("//li//a[text()='" + term + "']")
    

       category = a.page.at("//li//a[text()='#{term}']")
    

    例如:

    >> a="In quotes" #=> "In quotes"
    
    >> puts "This string is \"#{a}\""  #=> This string is "In quotes"
    >> puts "This string is '#{a}'"    #=> This string is 'In quotes'
    >> puts "This string is '"+a+"'"   #=> This string is 'In quotes'
    

    【讨论】:

    • 快速澄清问题 - 为什么第一个转义在引号之外,第二个在引号​​内? \"#{term}\"
    • 这里back slash用作转义字符。所以你在引号前使用back slash
    【解决方案2】:

    可能与您的问题相关的一个很少使用的功能是 Nokogiri 在评估 XPath 表达式时调用 ruby​​ 回调的能力。

    您可以在 Node#xpath (http://nokogiri.org/Nokogiri/XML/Node.html#method-i-xpath) 的方法文档下的 http://nokogiri.org 阅读有关此功能的更多信息,但这里有一个解决您问题的示例:

    #! /usr/bin/env ruby
    
    require 'nokogiri'
    
    xml = <<-EOXML
    <root>
      <a n='1'>foo</a>
      <a n='2'>bar</a>
      <a n='3'>baz</a>
    </root>
    EOXML
    doc = Nokogiri::XML xml
    
    dynamic_query = Class.new do
      def text_matching node_set, string
        node_set.select { |node| node.inner_text == string }
      end
    end
    
    puts doc.at_xpath("//a[text_matching(., 'bar')]", dynamic_query.new)
    # => <a n="2">bar</a>
    puts doc.at_xpath("//a[text_matching(., 'foo')]", dynamic_query.new)
    # => <a n="1">foo</a>
    

    HTH。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多