Why does this Nokogiri XPath have a null return?

给你一囗甜甜゛ 提交于 2019-11-28 10:01:05

问题


I'm XPath-ing through a web page with NOKOGIRI. I'm familiar with XPath, but I cannot figure out why my XPath fails to pick up the specific row. See the ruby code.

I used FireBug XML to validate my XPath, so I am 99% sure my XPath is correct.

require 'nokogiri'
require 'open-uri'

@searchURL = 'http://www.umn.edu/lookup?UID=smit4562'
@xpath = '//html/body/p/table/tbody/tr/td[2]/table/tbody/tr[2]'

doc = Nokogiri::HTML(open(@searchURL))

puts 'row should be = Email Address: smit4562@umn.edu'
puts '=> ' + doc.xpath(@xpath).to_s

puts 'is row emppty?'
puts '=> ' + doc.xpath(@xpath).empty?().to_s

回答1:


The <tbody> tag is an optional tag which is implicit if it is omitted. This means the <tbody> tags are inserted automatically by the browser when not present. They are not in the source code in your example, so nokogiri doesn't know about them.

Firebug uses the generated DOM, which does contains the tbody elements, so the statement does match inside a browser.

Remove both the tbody selectors and you should be fine.



来源:https://stackoverflow.com/questions/9156650/why-does-this-nokogiri-xpath-have-a-null-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!