cdub
cdub

Reputation: 410

Python-Selenium: Wait for an element to exist then return True or false

I am trying to create a function to help determine if an element appears or disappears from a web page.

This is what I have.

def wait_for_element_to_exist(driver, by, seconds=15, negative=False):
    wait = WebDriverWait(driver, seconds)

    # waiting for element to exist
    if not negative:
        try:
            wait.until(EC.presence_of_element_located(*by))
            return True
        except:
            return False

    #wait for element not to exist
    else:
        try:
            wait.until_not(EC.presence_of_element_located(*by))
            return True
        except:
            return False

Only thing is that it always returns FALSE no matter how how call it or if the element is present

wait_for_element_to_exist(self.driver, (By.XPATH, 'xpath')) returns False

wait_for_element_to_exist(self.driver, (By.CLASS, 'class'), negative=True) returns False

What am I doing wrong?

Upvotes: 1

Views: 3081

Answers (2)

Jeremy Kahan
Jeremy Kahan

Reputation: 3826

The problem you are having is with your call on presence_of_element_located(*by)

It's throwing a TypeError, because *by unpacks into two elements, which is one more than it expects. Change *by to by.

Once you do, if you say on this page,

wait_for_element_to_exist(browser, (By.ID, 'question-header'))

it returns True

and wait_for_element_to_exist(browser, (By.ID, 'timeout-header')) returns False.

I would recommend changing your except to except TimeoutException after saying:

from selenium.common.exceptions import TimeoutException

When I have written similar functions, I passed the locate method and the associated string as separate parameters, which may be easier to read and debug.

Upvotes: 2

osint_alex
osint_alex

Reputation: 1022

I think your code is going wrong because you are using a try except block. If Selenium doesn't find the element I don't think it finds an error - it just returns None.

So in similar code I've written in the past for this problem, I've done something like this:

element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, "h2"))
        )

if element:
    return True
else:
    return False

So applied to your code that would look like this:

def wait_for_element_to_exist(driver, by, seconds=15, negative=False):
    wait = WebDriverWait(driver, seconds)

    # waiting for element to exist
    if not negative:
        wait_result = wait.until(EC.presence_of_element_located(*by))
        if wait_result:
            return True
        else:
            return False

    #wait for element not to exist
    else:
        wait_result = wait.until_not(EC.presence_of_element_located(*by))
        if wait_result:
            return True
        else:
            return False

Hope that works?

Upvotes: 1

Related Questions