【问题标题】:Nokogiri and Xpath queryNokogiri 和 Xpath 查询
【发布时间】:2012-07-06 17:52:59
【问题描述】:

我在循环中有这个 Xpath 查询,

//div[@class='listing_content'][#{i}]/div/div/h3/a/text()

我想单独处理每个节点

问题是它给出了正确的节点,但同时所有节点都一次完成。

还有i > 1的时候什么都不返回?

for i in (1...30)
  name = page.xpath("//div[@class='listing_content'][#{i}]/div/div/h3/a/text()")
  puts "this is name"
  puts name

  #Get Business phone
  phone = page.xpath("//div[@class='listing_content'][#{i}]//span[@class='business-phone phone']/text()")
  puts "this is phone"
  puts phone

  #Get Business website(if any)
  puts "this is website"
  website = page.xpath("//div[@class='listing_content'][#{i}]//li[@class='website-feature']//@href")
  puts website
end

【问题讨论】:

  • 您能发布您正在使用的标记吗?
  • 原谅我的无知什么是标记?
  • 提示:XML 代表什么?

标签: ruby xpath nokogiri


【解决方案1】:

同样当 i > 1 时,它什么也不返回?

这是 XPath 中第二常见的常见问题解答:

使用

(//div[@class='listing_content'])[#{i}]/div/div/h3/a/text()

观察到的行为的原因是在 XPath 中 [] 的优先级(优先级)高于 // 伪运算符。

因此,在您的原始表达式中,您指定应选择作为其父级的 i-th 子级的每个 div[@class='listing_content'] 元素。

但是,在您正在使用的 XML 文档中,每个 div[@class='listing_content'] 恰好是其父级的第一个(也是唯一一个)子级 - 因此如果 i > 1 则没有选择任何内容。

与任何其他语言一样,为了覆盖默认优先级,我们必须使用括号。

【讨论】:

  • 有错字吗?如果我在括号之间添加括号,它不会编译。
  • @Mtl-z Mark:不,我成功运行了这个:(//div[@class='listing_content'])[1]/div/div/h3/a/text()
  • 好吧,我复制/粘贴错误。非常感谢,它正在工作,我现在明白我的错误了。
  • @Mtl-zMark:我很高兴这个答案对你有用。请您点击旁边的复选标记接受答案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多