Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 928
Chris Avatar asked Aug 05 '11 15:08

Chris


1 Answers

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.

like image 79
mu is too short Avatar answered Nov 01 '22 06:11

mu is too short