0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pyautoguiを使った画像認識で、画像が見つかるまで探索を繰り返す方法

Posted at

背景

pythonでRPAツールを作る際、pyautoguiを使うことは多いと思います。
pyautoguiを使う理由として、画面上に表示されている特定の画像を探索してクリックさせる動作をさせたいというのがあると思います。
例えば、下記のように

target_click.py
#'target.png'という画像を探してクリックする
a = pyautogui.locateOnScreen('target.png', confidence=0.8)
pyautogui.moveTo(a)
pyautogui.click()

しかし、対象の画像が画面上に見つからなかった場合、エラーで終了してしまいます。

解決策

下記のように記述することで、対象画像が見つかるまで探索を繰り返すことができます

target_click_retry.py
while True:
    try:
        #'target.png'が見つかればbreakで抜けます
        if pyautogui.locateOnScreen('target.png', confidence=0.8):
            break
    # 「except pg.ImageNotFoundException」で画像認識できなかった時の動作を指定
    except pyautogui.ImageNotFoundException:
        print("retry") #ここはお好きに
        time.sleep(1)
        continue

#ここは一緒
a = pyautogui.locateOnScreen('target.png', confidence=0.8)
pyautogui.moveTo(a)
pyautogui.click()

繰り返す回数をfor文で指定して、見つからない場合タイムアウトさせるのもよいでしょう

誰かの参考になればうれしいです

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?