简体   繁体   English

将Ruby嵌入xpath / Nokogiri

[英]Embed Ruby in xpath/Nokogiri

Probably a pretty easy question: 可能是一个很简单的问题:

I'm using Mechanize, Nokogori, and Xpath to parse through some html as such: 我正在使用Mechanize,Nokogori和Xpath通过一些html进行解析,例如:

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

Now, I want the term that I'm searching for in text()= to be dynamic...ie I want to create a local variable: 现在,我希望在text()=搜索的术语是动态的...即我想创建一个局部变量:

term = 'Test'

and embed that local ruby variable in the Xpath, if that makes sense. 并在Xpath中嵌入该本地ruby变量(如果可以的话)。

Any ideas how? 有什么想法吗?

My intuition was to treat this like string concatenation, but that doesn't work out: 我的直觉是将其视为字符串连接,但这行不通:

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

When you use category = a.page.at("//li//a[text()=" + term + "]") . 当您使用category = a.page.at("//li//a[text()=" + term + "]") The final result to method is //li//a[text()=Test] where test is not in quotes. 方法的最终结果是//li//a[text()=Test] ,其中test不在引号中。 So to put quotes around string you need to use escape character \\ . 因此,要在字符串两边加上引号,您需要使用转义字符\\

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

or 要么

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

or 要么

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

For example: 例如:

>> 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'

A little-used feature that might be relevant to your question is Nokogiri's ability to call a ruby callback while evaluating an XPath expression. 可能与您的问题有关的一个很少使用的功能是Nokogiri在评估XPath表达式时调用ruby回调的功能。

You can read more about this feature at http://nokogiri.org under the method docs for Node#xpath ( http://nokogiri.org/Nokogiri/XML/Node.html#method-i-xpath ), but here's an example addressing your question: 您可以在http://nokogiri.orgNode#xpath方法文档( http://nokogiri.org/Nokogiri/XML/Node.html#method-i-xpath )的方法文档下阅读有关此功能的更多信息。解决您的问题的示例:

#! /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. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM