13

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

I want the opposite, when the element is not present.
you mean, you want to wait for element become invisible/unpresent?
invisibility of element is a bit different from presence of element, so this is not a precise answer to this question. The above is an answer to a different but very similar question about invisibility.
A closing bracket ")" is missing from the function.
I would add try/except to this code. What if an element is not present? There will be StaleElementReferenceException
11

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(...)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.