Search code examples
pythonseleniumselenium-webdriverpytestwebdriverwait

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?


Solution

  • 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.