'How do I wait for pyautogui.locateonscreen() to return a value?

I am creating a webbot and I want to wait for a certain image to appear on the webpage before I continue my script.

I am making use of pyautogui.locatesonscreen() function, but I can't find a way to keep locating the object until it appears.

My script just seems to run the locateonscreen function once before it returns a value of none - I want it to keep looping untli it finds the image.



Solution 1:[1]

You can loop the script:

import pyautogui
image = pyautogui.locateOnScreen("image.png")

#Searches for the image
while image == None:
    image = pyautogui.locateOnScreen("image.png")
    print("still haven't found the image")

#When program finds image, print the location
print(image)

Solution 2:[2]

I know this post is two years old, but I found this asking the same questions and the provided solution does not work with pyautogui v0.9.41 and above. So here's my own:

import pyautogui


location = None
imageFile = 'image.png'

while (location == None):
    try:
        location = pyautogui.locateOnScreen(imageFile)
    except Exception as e:
        print(e)

print(location)

From pyautogui.readthedocs.io: NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None.

Solution 3:[3]

Don't know why but the above solution is not working for me! maybe because it is looking for 100% match of the image, so to prevent this exception use confidence parameter! you can see more about it at PyAutoGUI’s documentation!

import pyautogui
import time
game_over =False
time.sleep(5)
while not game_over:
    try:
        x1, y1=pyautogui.center(pyautogui.locateOnScreen("./pyautogui_img/green_tik.JPG", confidence=0.7)) 
        time.sleep(2)
        pyautogui.moveTo(x1,y1)
        print('Hurray! image found')
        game_over = True
    except:
        print(f'image not found trying again in next 5 seconds. ')
        time.sleep(5)

The above code is going to look for an image and if not found then going to try again in next 5 seconds, until the image not found it will keep running! and also to use it make sure you installed opencv and pillow too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SAM123
Solution 2 Gunnar
Solution 3