开发者

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

开发者 https://www.devze.com 2023-03-26 08:45 出处:网络
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?

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 do开发者_开发百科es 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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号