我有一个使用 pyautogui.locateOnScreen 在屏幕上搜索图像的脚本。在我的个人计算机上,如果找不到图像,则会转到 elif 分支(这是完美的)。但是,在我的工作计算机上,如果找不到图像,则会引发异常 ImageNotFoundException 并停止执行。
` 如果 pyautogui.locateOnScreen('img/run.png',grayscale=False,confidence=0.6) 不是 None: locationrun1 = pyautogui.locateCenterOnScreen('img/run.png', 灰度=False, 置信度=0.8) pyautogui.moveTo(locationrun1) pyautogui.click() print(“逃跑”)
elif pyautogui.locateOnScreen('img/run2.png', grayscale=False, confidence=0.6) is not None:
time.sleep(random.uniform(1.8, 2.1))
keyboard.press("w")
locationrun2 = pyautogui.locateCenterOnScreen('img/run2.png', grayscale=False, confidence=0.8)
pyautogui.moveTo(locationrun2)
pyautogui.click()`
如何解决此问题并确保不同计算机之间的行为一致?
测试这一点的最佳方法是使用具有代表不同配置(即您的工作计算机和家庭计算机)的不同图像的单元测试。您可以使用
pytest
轻松实现此目的,方法如下:
import pytest
from PIL import Image
def test_clicks_images(monkeypatch):
def fake_screenshot(*args, **kwargs):
# Fake the pyscreeze screenshot function so it returns the previously saved image
# instead of taking a screenshot
im = Image.open(f"path/to/previously/saved/screenshot.png")
im.load()
return im
monkeypatch.setattr("pyscreeze.screenshot", fake_screenshot)
#ensure that img/run2.png is found in screenshot.png thus ensuring that it will find it in the computer producing that screenshot
assert len(pyautogui.locateOnScreen('img/run2.png', grayscale=False, confidence=0.6)) != 0
确保用于测试的屏幕截图尽可能接近环境复制非常重要(无需重新缩放或任何其他操作)