windows 桌面GUI自动化- 14.pywinauto 找到多个相同控件使用found_index

发布时间 2023-08-24 16:30:04作者: 上海-悠悠

前言

pywinauto 在查找到多个相同控件时操作会报错,可以使用found_index 选择其中的一个

查找到多个

查找control_type="MenuBar" 的所有控件

from pywinauto import Application


app = Application('uia').start("notepad.exe")
win = app.window(title_re="无标题 - 记事本")
# 输入内容
win.child_window(title="文本编辑器").set_text("hello world")

# 查找MenuBar
menu = win.child_window(control_type="MenuBar")
print(menu.window_text())

在获取窗口文本menu.window_text() 时会报错,因为不止找到一个

pywinauto.findwindows.ElementAmbiguousError: There are 2 elements that match the criteria 
{'control_type': 'MenuBar', 'top_level_only': False, 'parent': <uia_element_info.UIAElementInfo - '无标题 - 记事本', Notepad, 460858>, 'backend': 'uia'}

加上 found_index 参数,按索引取值

# 查找
menu = win.child_window(control_type="MenuBar", found_index=0)
print(menu.window_text())

索引下标从0开始