PythonのPyAutoGUIを使ってタスクを自動化する方法を学びましょう。
私たちは、繰り返しが必要な作業に出くわすと、それを避けるために特別に方法を考えようとします。
それが人間の性です。
同じ作業を一生懸命やっているうちに、どこかで「自動的に機能するもの、決められた条件さえ満たせば動くものを作ればいい」という考えに行き着くのです。
例えば、電池と草原を必要とする芝刈り機であり、同じ行を何度も印刷するコードです。
自動化は私たち人間の生活の中で大きな部分を占めており、自動化で作業することで、その間に他の作業に集中することができます。
しかし、自動化には作業するためのツールが必要であり、そこで pyautogui モジュールが登場します。
pyautogui` モジュールは、実行中のスクリプトがマウスとキーボードを制御し、システム上のユーザーが行うのと同じように入力を提供し、システム上のアプリケーション間のインタラクションを可能にすることができるようにします。
PyAutoGUIをPythonにインストールする
PyAutoGUIをPythonにインストールするには、PIPパッケージマネージャを使用します。
pipが動作するOSであれば、同じ行程でインストールすることができます。
# Windows does not have any dependencies for installationpip install pyautogui
# Mac has two dependencies for PyAutoGUIpip3 install pyobjc-core
pip3 install pyobjc
pip3 install pyautogui
# Linux distributions require a single dependency installedpip3 install python3-xlib
pip3 install pyautogui
|
依存関係(もしあれば)とモジュールのインストールが完了したら、出発です!
Python で作業する PyAutoGUI
PyAutoGUIが提供する素晴らしい機能をPythonで使用する前に、まずスクリプトでこのモジュールをインポートする必要があります。
# Importing the PyAutoGUI moduleimport pyautogui as pag
|
この記事の中では、pyautoguiモジュールのエイリアスを使用します。
1. PyAutoGUIの基本関数
スクリプトを作成する前に、どのコンポーネントがどのような種類のタスクを実行するかを知っておくとよいでしょう。
Pythonのpyautoguiは、入力を扱うためのさまざまなメソッドを提供しています。
# Gets the size of the primary monitor.screenWidth, screenHeight = pag.size()
# Gets the XY position of the mouse.currentMouseX, currentMouseY = pag.position()
# Move the mouse to XY coordinates.pag.moveTo(100, 150)
# Allows the script to click with the mouse.pag.click()# Move the mouse to XY coordinates and click it.pag.click(100, 200)
# Find where button.png appears on the screen and click it.pag.click('button.png')
# Double clicks the mouse.pag.doubleClick()# The writing functionality provided by PyAutoGUI imitates keyboard inputpag.write('Hello world!')
# Presses the Esc key.pag.press('esc')
# The keyDown button causes the script to hold down on a specific key.pag.keyDown('shift')
# You can pass a list of keys to press, which will be consecutively executed.pag.press(['left', 'left', 'left', 'left'])
# Lets go of a certain key.pag.keyUp('shift')
# The hotkey() function allows for a selection of keys for hotkey usage.
pag.hotkey('ctrl', 'c')
# Make an alert box appear and pause the program until OK is clicked.pag.alert('This is the message to display.')
|
また、このモジュールはスクリプトで動作するためのキーワードを提供しており、これは pyautogui.KEY_NAMES によってアクセスすることができることも重要な点です。
2. PythonのPyAutoGUIを使用したシンプルな自動化
Pythonとpyautoguiモジュールを少し使うだけで、どんなプラットフォームでもメッセージを継続的に送信するシンプルなスパム自動化ツールを作ることができます。
まず、必要な関数を操作するために、いくつかのモジュールをインポートしましょう。
# Importing the pyautogui moduleimport pyautogui as pag
# Importing time to delay the input speedimport time
# Working with Tkinter allows us to use a GUI interface to select the file to read fromfrom tkinter import Tk
from tkinter.filedialog import askopenfilename
|
さて、スパムボットを作るにはどうしたらいいのでしょうか。
2.1. 入力手段を用意します。
メッセージを手入力することで入力を提供することもできますが、、、それではメッセージスパムの自動化すら目的から外れてしまいます。
そこで、ファイルを解析して、その内容をプラットフォームに書き込むという作業をやってみましょう。
ここでは、tkinterモジュールを使って、読み込むファイルを選択することにします。
# The withdraw function hides the root window of TkinterTk().withdraw()# The askopenfilename() takes the file path from user selection.filename = askopenfilename()
|
さて、askopenfilename()関数を通して、ファイルのパスを取得しました。
このパスは filename 変数に格納されます。
2.2. スパムの速度を調整する遅延を作成します。
また、各メッセージの間に遅延を設けて、プラットフォームの入力遅延により1つのメッセージが上書きされるのではなく、1つずつメッセージを受け取れるようにする必要があります。
# We take the input of the user and strip it such that we only receive a numeric input.timeDelay = int(input("If you want a delay, enter the number of seconds for the delay : ").split()[0])
# In case the input time is designed to break the delay function, we can reset the timeDelay back to 1.if timeDelay < 1:
timeDelay = 1
# We need to place the cursor in the right place to begin writing to the platform.time.sleep(5)
|
2.3. PyAutoGUIを使ったスパム!
これで pyautogui モジュールを使って、ファイルからすべての単語を読み込んで、プラットフォームに書き込むことができます。
f = open(filename, "r")
for word in f:
time.sleep(timeDelay)
pag.typewrite(word)
pag.press("enter")
|
3. PythonによるPyAutoguiの完全な実装
これでコードは完成です。
最終的には以下のようなコードになります。
import pyautogui as pag
import time
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw()filename = askopenfilename()
print(filename)
timeDelay = int(input("If you want a delay, enter the number of seconds for the delay : ").split()[0])
if timeDelay < 1:
timeDelay = 1
time.sleep(5)
f = open(filename, "r")
for word in f:
time.sleep(timeDelay)
pag.typewrite(word)
pag.press("enter")
|
まとめ
この記事を読み終えた今、あなたはPythonのpyautoguiが何を提供し、何に使えるかを知っています。
スパムをすることは必ずしもお勧めしませんが、いじくり回すことは全く問題ありません。
他の記事、Pandasモジュール、Numpy配列、Pygameを使ったHi-Loゲームの作成もご覧ください。