Wait until element is not present

Question:

I’m using selenium in Python 2.7 and I have this code, but I’m looking for a more efficient way to do this:

while True:
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, 'button'))
        )   
    except:
        break
Asked By: User

||

Answers:

 element = WebDriverWait(driver, 10).until(
            EC.invisibility_of_element_located((By.ID, 'button')))

you don’t need to use while. it already waits for time that you present in WebDriverWait() function.

Answered By: Mahsum Akbas

1) Use staleness_of from expected condition

class staleness_of(object):
""" Wait until an element is no longer attached to the DOM.
element is the element to wait for.
returns False if the element is still attached to the DOM, true otherwise.
"""

2) WebDriverWait(driver, 10).until_not(…)

Answered By: dmr

You can make a custom wait condition. Maybe this is what you want:

class absence_of_element_located(object):
"""An expectation for checking that an element is not present.

    locator - used to find the element
    by - how the search is to be made
    """

def __init__(self, by: By.ID, locator: str):
    self.locator = locator
    self.by = by

def __call__(self, driver) -> bool:
    elemento = driver.find_elements(self.by, self.locator)

    if not elemento:
        return True
    else:
        return False

You could then use it:

WebDriverWait(browser, 10).until(ElementoNaoLocalizado(By.ID, "button"))

I believe a problem of this is that it finds all objects that correspond to your search. In a bigger site, a change may be needed.

Answered By: Schilive
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.