【前提】
UI Automationを使用。
from pywinauto import Desktop
# UIAバックエンドを使用することを明示的に指定
app = Desktop(backend="uia")
【要素を取得】
すべてのトップレベルウィンドウ情報を取得する
コマンドラインで取得
以下のpythonスクリプトを実行する。
from pywinauto import Desktop
desktop = Desktop(backend="uia")
all_windows = desktop.windows()
for w in all_windows:
print(f"Title: {w.window_text()}")
Accessibility Insightsで取得
- Accessibility Insightsを起動する。
- "Live Inspect"状態にする。
- 対象ウインドウをクリックする。
- 他の要素が選択されないように、Accessibility Insightsで"Pause"ボタンをクリックする。
- Accessibility Insightsで"ウインドウ 〇〇"をクリック。
- Accessibility Insightsの"Name"項目は、スクリプト内の"title"に該当する。
- 公式ページでAccessibility Insightsアプリを取得する。
特定ウィンドウの子要素確認
コマンドラインで取得
以下のpythonスクリプトを実行する。
※例として対象ウインドウを「クロック」アプリとする。
from pywinauto import Desktop
target_win = Desktop(backend="uia").window(title="クロック", control_type="Window")
target_win.set_focus()
target_win.print_control_identifiers()
Accessibility Insightsで取得
上述の「Accessibility Insightsで取得」と同じ。
【同じ名前の要素から一つを指定】
目的
画面に同じ名前のボタンやテキストボックスが複数ある時に、その中の一つを指定して操作する。
方法
親要素を経由して目的の要素を特定する。
親要素を指定してから、その中から目的の要素を指定する。
例
日本語とスペイン語の「・・・」は、どちらも「Title = "その他のオプション"」である。
階層構造の理解
---- 設定ウィンドウ (Window) ----
- 日本語語グループ (Group)
- その他のオプション (Button) ← これではない
- その他の要素...
- スペイン語グループ (Group)
- その他のオプション (Button) ← これを選択したい
- その他の要素...
スクリプトの書き方
以下は、スペイン語の方を選択する場合のスクリプト。
from pywinauto import Desktop
import time
target_win = Desktop(backend="uia").window(title="設定", control_type="Window")
target_win.set_focus()
time.sleep(1)
target_area = target_win.child_window(title="スペイン語 (スペイン)", control_type="Group")
target_item = target_area.child_window(title="その他のオプション", control_type="Button")
item_to_do = target_item.wrapper_object()
item_to_do.click_input()
【マウスカーソルを動かすと消えてしまう要素の操作】
マウスカーソルを動かすと消えてしまう要素(ドロップダウンメニューのアイテム、ポップアップメニューなど)を操作する場合、pywinauto の click() メソッドが最適です。
| メソッド | 動作 | 消える要素での挙動 |
|---|---|---|
click_input() |
実際にマウスカーソルを移動し、物理的なクリック操作をシミュレートする | カーソルが要素の位置に移動する瞬間に、要素が消えてしまい、クリックに失敗する可能性が高い |
click() |
対象の要素にクリックのWindowsメッセージを直接送信する | マウスカーソルは移動しないため、要素が消えることなく、裏側で操作を実行できる |
補足
click() は、ウィンドウメッセージを送ることで操作するため、要素が画面上に表示されている必要は必ずしもありません。ウィンドウの内部的な状態がクリックを受け付ける状態であれば、カーソルが原因で要素が非表示になる問題を回避できます。
ComboBoxで選択されている値を取得する
# 対象コンボボックスをクリック
target_combo = target_win.child_window(auto_id=XXXXX, control_type="ComboBox")
target_combo.wrapper_object().click_input()
# 選択されたテキストを表示する
selected_item = combo.selected_text()
print(f"{selected_item}")

