mihalp mihalp - 5 months ago 5x
Ruby Question

Define variable by elements class even not displayed on current page

I'm using Ruby and Selenium to get some data from a page. I want to define variable with

, but element is not currently visible on page.

next = driver.find_element(:class, 'right')

It returns

It works fine when element is present.
Any solutions?
Thank you!


Selenium works by executing Javascript commands. By using find_element it will search for the element on the DOM. If it cannot find it you will get the error you are getting. After all if an element is not on the DOM it cannot be found.

The real question is why do you want too find an element that is not currently present on the DOM? You can't do anything with somehing that doesn't exist.

All I could think of is that the element becomes present after the DOM has been loaded due to Javascript not being fully executed yet. If that is the case you can use a WebDriver::Wait to try and find the element for a certain amount of time.

A small example: wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds begin element = wait.until { driver.find_element(:id => "some-dynamic-element") } ensure driver.quit end

Edit to include try-catch example:

    next = driver.find_element(:class, 'right')
    # Code for when element is found here
rescue NoSuchElementError
    # Code for when element is not found here