提问者:小点点

搜索图像不存在时的Pyautogui定位屏幕处理


我试图在软件中制作多个屏幕截图,有时软件会显示错误消息。当该消息出现时,我想单击它(而不是制作屏幕截图),然后移动到下一部分来制作该消息的屏幕截图。

我正在使用Pyautogui来完成它,因为它以前非常有用。但是这一次,由于显示了这个错误消息,我在处理它时遇到了麻烦。Pyautogui具有在屏幕截图上定位特定部分的功能,但是当它不在屏幕截图上时,它会创建一个错误,而不是给出False。

我的第一个想法是使用if语句,但是缺少搜索图像会导致程序崩溃,我尝试了try/except组合,但现在它产生了一些无用的循环。

你能看看我当前的代码并帮我修复它吗?

import time
import pyautogui

counter = 0
dimensions = (50,0,1000,1000)

time.sleep(5) # waiting 5 seconds before taking screenshots

while counter < 10 :
    time.sleep(1) # waiting 1 second

    im = pyautogui.screenshot(region=dimensions)
    filename = str(counter) +"_PAGE1" + ".png" 
    im.save(filename) # saves the screenshot in a file

    time.sleep(1) # waiting 1 second
    pyautogui.press('enter') #make the software go the next page


    try
        pyautogui.locateOnScreen('errormessage.png'):
        pyautogui.press('enter') #click OK on the error message
        pyautogui.press('up') #go to the next line in the software
        counter += 1
        continue #to start over the while loop
    except:
        pass

    im = pyautogui.screenshot(region=dimensions)
    filename = str(counter) +"_PAGE2" + ".png"
    im.save(filename) # saves the screenshot in a file

    time.sleep(1) # waiting 1 second
    pyautogui.press('escape') #go back to previous page
    pyautogui.press('up') #go to the next line in the software
    counter += 1

所以我从软件中的一行开始,截图,点击回车键。此时,要么出现一条错误消息,然后我想单击它上的OK,然后移动到下一行(向上),增加计数器并开始while循环。要么显示下一页,我想截屏,点击escape返回,然后移动到下一行(向上),增加计数器并开始while循环。

正如我上面所说,我尝试了几种不同的变体,但迄今为止没有成功。(使用if语句将代码放入except而不是“pass”中…)

我希望我的解释足够清楚。正如您所看到的,我基本上是Python的初学者,但我会努力提高自己的技能,非常感谢您的帮助。

干杯,萨姆


共1个答案

匿名用户

所以在尝试了一大堆东西后,我终于找到了一个变通方法。我确实使用了if语句和一个肮脏的把戏:

if str(pyautogui.locateOnScreen('errormessage.png')) != "None":

而且它做的很好!

享受生活!