Search code examples
pythonpython-3.xwaitsleeppolling

Write a Python function that waits and listens until a condition is met, similar to WebDriverWait().until()


Generally, I want to write a function that wait until a condition is met.

Specifically, i want it to wait until an element exist or not exist, so the moment this element exist i want my script to know without any delay and continue.

In more details, in a "while True" loop , i want my script to wait until the moment an element exist (a condition is met to be more general) then it prints the time of the displaying of this element, then it waits again until this element disappear , then it prints the time of the disappearance . and repeat.

It means something similar to the " WebDriverWait().until() " used in selenium, but i want to write my own function in python and without using a third-party library so that i can use it even when not using selenium or any other library.

while true:
    element = WebDriverWait(driver, 28800).until(
        EC.visibility_of_element_located(
           (By.XPATH, "//span[@title = 'online']")))
    print(online_time)

    element = WebDriverWait(driver, 28800).until(
    EC.invisibility_of_element_located(
        (By.XPATH, "//span[@title = 'online']")))
    print(offline_time)

I already searched and what i found is a bunch of answers that recommend using the sleep() function with conditions, the wait() function , or coding some sort of listener, and also talking about the polling concept that i really don't understand.

Unfortunately i tried working with sleep() function but i couldn't write any code worth posting here as an attempt of achieving my wanted behavior, because i don't know when the element will be displayed, how much time it will exist and when it will disappear again. so working with an exact amount of seconds is worthless, i think.

I hope you can help me write it or at least lead me to the right path.

Any explanation of the concepts i talked about is welcomed. PS: I'am a beginner programmer.


Solution

  • This might be difficult to generalise in the way you're thinking about it. Often, you don't want to wait for things. It's better to do other stuff or do nothing. Python has an entire library dedicated to handling this kind of thing. it's called asyncio.

    Conceptually, all you need a function that will tell you if some action is complete, and a while loop.

    import time    
    while not action_is_complete():
        sleep(10)
    

    This will keep going until action_is_complete() returns true. Then your program will continue executing.