Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether element is present

Is there anyway to check whether an element is present in Selenium web driver? I try to use this code:

if @driver.find_element(:link, "Save").displayed? == true

but it will break in exception, which is not what I expected because I still want the script to continue running.

like image 669
Thanh Avatar asked Dec 03 '12 04:12

Thanh


1 Answers

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
like image 63
Igor Khrol Avatar answered Sep 20 '22 10:09

Igor Khrol