Check if item is present

Is there a way to check if an element is present in the Selenium web driver? I am trying to use this code:

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

but it will be broken into an exception, which I did not expect, because I still want the script to continue to work.

+7
source share
4 answers

@driver.find_element throws an exception called NoSuchElementException .

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

+6
source

I am not a Ruby expert and can make some syntax errors, but you can get a general idea:

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

This code does not throw a NoSuchElementException

But this method will freeze for a while if you have implicitlyWait greater than zero and there are no elements on the page. The second problem: if the element exists on the page but is not displayed, you will get true .

So the workaround is trying to create a 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 
+8
source

If he expected the element to be on the page, no matter what it seems to me to be useful to use a selenium wait object with element.displayed? , instead of 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 when parts of the page take longer to render properly than others.

+1
source

Please see the link below for a solution.

http://code.google.com/p/selenium/wiki/RubyBindings

-4
source

All Articles