我正在尝试在一个软件中制作多个屏幕截图,有时该软件会显示错误消息。当出现该消息时,我想单击它(而不是截屏),然后移到下一部分以截屏。
我正在使用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
所以我从软件的第一行开始,截图,然后按Enter。此时,出现一条错误消息,然后我要在其上单击“确定”,然后移至下一行(向上),递增计数器并从while循环开始。无论显示下一页,我都想截图,然后按Escape键返回,然后移至下一行(向上),增加计数器并从while循环开始。
如上所述,我尝试了几种不同的变体,但到目前为止没有成功。 (使用if语句将代码放入except中,而不是“ pass”中。)
我希望我的解释足够清楚。如您所见,我几乎是Python的初学者,但我会努力提高自己的技能,非常感谢您的帮助。
欢呼,山姆
因此,在尝试了一堆东西之后,我终于找到了解决方法。我确实使用了if语句和一个肮脏的把戏:
if str(pyautogui.locateOnScreen('errormessage.png')) != "None":
它确实完成了工作!
享受生活!