Search code examples
pythonpython-3.xappiumpytest

Python: Print Text Of Element Each Second For A Certain Amount Of Time


I have problems with printing each second an element that is refreshed in the application (android appium).

I have an app that generates a text each second and I need to print that information for 60 seconds.

I have tried using the WebDriver Wait I tried as well the time.sleep, even the threading.Timer but that one requires a function call and since I am beginner I have a problem with nested functions for pytest

Using timer:

def testSignal(i):
         dbm = self.driver.find_element_by_id("com.ubnt.usurvey:id/vSignal")
         print(dbm.text)
         sys.stdout.write(str(i) + '\r')
         sys.stdout.flush()
         i += 1
         threading.Timer(1, testSignal, [i]).start()

Using WebDriverWait:

wait = WebDriverWait(self.driver, 60, poll_frequency=1)
dbm = wait.until(EC.presence_of_element_located((By.ID,"com.ubnt.usurvey:id/vSignal")))
text = dbm.text
print(text)

Using time.sleep:

dbm = self.driver.find_element_by_id("com.ubnt.usurvey:id/vSignal")
text = dbm.text
print(text)
time.sleep(60)

I am new with this and I have problems on looping the print based on searching an element (After reload).


Solution

  • I did not understand your code but i think this will work.

    dbm = self.driver.find_element_by_id("com.ubnt.usurvey:id/vSignal")
    while True:
        text = None
        try:
            text = dbm.text
        except:
            pass
        if not text:
            break
        print(text)
        time.sleep(1)
    

    If you want to stop it by CTRL + C (KeyboardInterrupt) and don't want to stop or crash the code, you can add another try:

    dbm = self.driver.find_element_by_id("com.ubnt.usurvey:id/vSignal")
    try:
        while True:
            text = None
            try:
                text = dbm.text
            except:
                pass
            if not text:
                break
            print(text)
            time.sleep(1)
    except KeyboardInterrupt:
        print("Loop stopped in a controlled manner.")