0

When looking at a dynamic element on a webpage, Selenium crashes if the element is not present. As a result I'm having to rescue the application to continue. I figure I'm doing something wrong with the syntax

response = driver.find_element(:class, element).text

If the element is not found, Selenium errors and crashes the application. This happens regardless of my browser configuration.

user1793514
  • 47
  • 1
  • 8

2 Answers2

1

Selenium is not crashing. Your code has encountered an exceptional condition (attempting to work with an element that is not there). The code is correctly responding to that exceptional condition by raising a NoSuchElementError.

If you are trying to determine if an element is there, you can use Driver#find_elements and check if the Array#size equals 0.

If you are trying to work with an element that is not yet on the page, you'll need to create an explicit wait to poll for the element to show up as in DebanjanB's answer.

titusfortner
  • 4,099
  • 2
  • 15
  • 29
0

You need to wait a bit for the element to be visible before you try to locate it as follows:

wait = Selenium::WebDriver::Wait.new(:timeout => 10)
ele = wait.until { driver.find_element(:class, element).displayed? }
response = ele.text
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • The issue is not waiting for the element to show up, it is actually not there. – user1793514 Dec 05 '21 at 22:26
  • If the issue is not being there or not you will have to fix any errors occuring from finding the element before getting it's .text. – Arundeep Chohan Dec 05 '21 at 22:58
  • 1
    One thing to note with this answer is that Selenium differentiates between an element being identifiable in the DOM and it being displayed on the page. This code may exit from the wait while the element is still not interactable. You might prefer: `wait.until { driver.find_element(:class, element).displayed? }` – titusfortner Dec 05 '21 at 23:09
  • @titusfortner your suggested code still would fail if element takes some time to exist. – Rajagopalan Dec 06 '21 at 00:55
  • 1
    @Rajagopalan Selenium automatically rescues `NoSuchElementError` when doing waits. https://github.com/SeleniumHQ/selenium/blob/trunk/rb/lib/selenium/webdriver/common/wait.rb#L40 – titusfortner Dec 06 '21 at 01:53
  • @titusfortner Looks like I met up with such an error in the past when I was using Java Binding. Let me check it again. Thanks for letting me know. – Rajagopalan Dec 06 '21 at 03:01