Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby - Why does this Nokogiri XPath have a null return?

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: [email protected]'
puts '=> ' + doc.xpath(@xpath).to_s

puts 'is row emppty?'
puts '=> ' + doc.xpath(@xpath).empty?().to_s
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...