How to check during Nokogiri/Ruby parsing if element exists on page?

Chris picture Chris · Aug 5, 2011 · Viewed 13.3k times · Source

how can I check during parsing of an HTML page with Nokogiri (Ruby gem) if an element, in this case a div, exists on the page?

On my test page, it does exist, so the pp yields the expected Nokogiri output. But the if statement does not work, the == true seems to be the wrong way to go about it. Any suggestions for improvement? Cheers, Chris

pp page.at('.//div[@class="errorMsg"]')

if page.at('.//div[@class="errorMsg"]') == true then
    puts "Error message found on page"
end 

Answer

mu is too short picture mu is too short · Aug 5, 2011

Comparing with true isn't the right way to go. The at call will return nil if it doesn't find anything so:

if page.at_css('div.errorMsg')
  puts 'Error message found on page'
else
  puts 'No error message found on page'
end

is one way as nil is falsey in a boolean context but a Nokogiri::XML::Node won't be. I also switched to CSS notation as I find that clearer than XPath for simple things like this but you're free to use at_xpath or feed XPath or a CSS selector to at if you like that better.

Also, the three at methods return the first matching element or nil so they're good choices if you just want to check existence.