Check whether element is present

I'm not Ruby expert and can make some syntax errors but you can get general idea:

if @driver.find_elements(:link, "Save").size() > 0

This code doesn't throw NoSuchElementException

But this method will "hang" for a while if you have implicitlyWait more than zero and there is no elements on the page. The second issue - if element exists on the page but not displayed you'll get true.

To workaround try to create method:

def is_element_present(how, what)
    @driver.manage.timeouts.implicit_wait = 0
    result = @driver.find_elements(how, what).size() > 0
    if result
        result = @driver.find_element(how, what).displayed?
    end
    @driver.manage.timeouts.implicit_wait = 30
    return result
end

@driver.find_element throws an exception called NoSuchElementError.

So you can write your own method which uses try catch block and return true when there is no exception and false when there is an exception.


If it's expected that the element should be on the page no matter what: use a selenium wait object with element.displayed?, rather than using begin/rescue:

wait = Selenium::WebDriver::Wait.new(:timeout => 15)
element = $driver.find_element(id: 'foo')
wait.until { element.displayed? } ## Or `.enabled?` etc.

This is useful in instances where parts of the page take longer to properly render than others.