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
Comparing with
trueisn’t the right way to go. Theatcall will returnnilif it doesn’t find anything so:is one way as
nilis falsey in a boolean context but aNokogiri::XML::Nodewon’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 useat_xpathor feed XPath or a CSS selector toatif you like that better.Also, the three
atmethods return the first matching element ornilso they’re good choices if you just want to check existence.