Cas
Cas

Reputation: 2267

How to use Selenium find_element_by_something function with no wait time if the element is not there?

Sometimes you want to do an action over an object that may or may not be in a page, obviously you would only want to execute the action if the object is present on the page, but if the object is not present that is also ok, but you don't want the automation to break. Right now, I have been handling this situation in two different ways:

Using a find_elements_by_something method along with an if:

my_var = driver.find_elements_by_xpath(some_xpath)
if len(my_var) > 0:
    # the element is present so do the action

Using a find_element_by_something method along with a try:

try:
    my_var =  driver.find_element_by_id(some_id)
    # do the action
except:
    # do something else

Both methods mentioned above work, but they have a big problem, they both make the automation slow because both try to find the element(s) using the driver timeout, so it can take a while.

Is there a way to try to find an element without using any timeout? If the element is not there in that instant in time that is ok, I don't want selenium to wait for it for a while, I just want to know if the element is there or not.

Solution:

Based on the response from @grumpasaurus

driver.implicitly_wait(0)
try:
    my_var =  driver.find_element_by_id(some_id)
    # do the action
except:
    # do something else
driver.implicitly_wait(old_wait_time)

Upvotes: 1

Views: 521

Answers (2)

grumpasaurus
grumpasaurus

Reputation: 712

I believe you're looking into an Explicit/Implicit Wait situation.

http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

Selenium allows you to change the implicit wait as you go through your test to change how long you want to wait for an element to show up. Technically you can change it to 0 have a rescue clause handy if you don't want to fail your test.

Upvotes: 2

barak manos
barak manos

Reputation: 30136

You can simply make sure it's in the page source before using any of the methods above.

For example:

str1 = 'id="'+some_id+'"'
str2 = "id='"+some_id+"'"
page_source = driver.page_source
if str1 in page_source or str2 in page_source:
    try:
        my_var = driver.find_element_by_id(some_id)
        # do the action
    except:
        # do something else

This should significantly reduce the number of times that you attempt to find an element which is not in the DOM (false-negative). Of course, if the element is dynamically added to the DOM on the client side (using Javascript), then you might revoke an attempt to find it when it's actually there (false-positive).

So you should make a careful inspection of the web-page before you choose to apply this method...

Upvotes: 1

Related Questions