首页 > 解决方案 > 当搜索到的图像不存在时 Pyautogui locateOnScreen 处理

问题描述

我正在尝试在软件中制作多个屏幕截图,有时软件会显示错误消息。当该消息出现时,我想单击它(而不是制作屏幕截图)并移至下一部分以制作屏幕截图。

我正在使用 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

所以我从软件的第一行开始,截图,回车。此时,要么出现一条错误消息,然后我想在其上单击“确定”,然后移动到下一行(向上),递增计数器并重新开始 while 循环。要么显示下一页,我想截屏,然后点击退出返回,然后移动到下一行(向上),增加计数器并从 while 循环开始。

正如我上面所说,我尝试了一些不同的变体,到目前为止都没有成功。(使用 if 语句将代码放在 except 而不是“pass”中......)

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

干杯,山姆

标签: pyautogui

解决方案


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

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

它做得恰到好处!

享受生活!


推荐阅读