Use of If function in Python with PyautoGUI

Viewed 31

by saving screenshots of google search box, and using through pyautogui, but can't able to do the task. Also I put all the required images in same Directory, there is no Directory error.

Task:

  1. wanted to add two variable of gSearch1 & gSearch2, if one fails or not found in place, just check another image instead which is gSearch2 with if function.
  2. Or if better & simple method is also possible, then please write that also.

Error: printing else: every time

My code:

import pyautogui

gSearch1 = pyautogui.locateOnScreen ('Google_URL_Blank1.png' , confidence=0.8)
gSearch2 = pyautogui.locateOnScreen ('Google_URL_Blank2.png' , confidence=0.8)

if gSearch1 == True: #if img1 found on screen run this condition
    pyautogui.click(gSearch1); pyautogui.typewrite( 'www.YouTube.com' , interval=0.5)

elif gSearch2 == True:  #if not found, then try to find img2 in this condition
    pyautogui.click(gSearch2); pyautogui.typewrite( 'www.YouTube.com' , interval=0.5)
else:
    print ('both imgs not found on screen')```

[enter image description here][1][enter image description here][2]


  [1]: https://i.stack.imgur.com/WGzz7.png
  [2]: https://i.stack.imgur.com/eB1d0.png
1 Answers

pyautogui.locateOnScreen() does not return any boolean value. It returns (left, top, width, height) coordinate of first found instance of the image on the screen. Raises ImageNotFoundException if not found on the screen. You can try this.

import pyautogui
try: 
    gSearch1 = pyautogui.locateOnScreen ('Google_URL_Blank1.png' , confidence=0.8)
    pyautogui.click(gSearch1); pyautogui.typewrite( 'www.YouTube.com' , interval=0.5)
except:
    try:
        gSearch2 = pyautogui.locateOnScreen ('Google_URL_Blank2.png' , confidence=0.8)
        pyautogui.click(gSearch2); pyautogui.typewrite( 'www.YouTube.com' , interval=0.5)
    except:
        print ('both imgs not found on screen')
Related