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

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

5
  • I want the opposite, when the element is not present.
    – User
    Sep 22, 2015 at 12:59
  • you mean, you want to wait for element become invisible/unpresent? Sep 22, 2015 at 13:00
  • 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.
    – justnpT
    May 29, 2020 at 8:18
  • A closing bracket ")" is missing from the function. Oct 18, 2020 at 5:42
  • I would add try/except to this code. What if an element is not present? There will be StaleElementReferenceException
    – vitaliis
    Oct 29, 2020 at 20:38
9

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.