如何解决pywinauto的ElementAmbiguousError:有2个与条件错误匹配的元素

问题描述

我正在尝试使用python和pywinauto自动运行Rufus
到目前为止,我已经能够运行可执行文件并在Rufus的主屏幕上修改控件。
在编写代码后,单击“开始”按钮,Rufus将显示一个弹出窗口。 此弹出窗口警告您USB密钥的全部内容将被删除。 我无法做的是连接到该弹出窗口,然后在此处按“确定”按钮。

这是我编写的代码:

# Connect to an existing window with title matching a regular expression
def ConnectWindow(exp):
  # Look for window matching regular expression
  try:
    handles = pwa.findwindows.find_windows(found_index=0,title_re=exp)
  except pwa.findwindows.WindowNotFoundError:
    handles = None
  # Make sure something was found
  if handles:
    # Make sure only one found
    if len(handles) > 1:
      print('Matched more than one window matching regular expression: {0}'.format(exp))
      sys.exit(1)
    # Return it!
    return pwa.Application().connect(handle=handles[0]).window()
  # Nothing found
  return None

popup = ConnectWindow('^Rufus$')
popup.set_focus()
pwa.keyboard.send_keys('{RIGHT}{ENTER}')

ConnectWindow会找到该窗口,并且弹出窗口的类型为pywinauto.application.WindowSpecification。
但是,每当我尝试对弹出窗口执行任何操作(例如set_focus)时,都会出现以下错误:

pywinauto.findwindows.ElementAmbiguousError:有两个与条件{'backend':'win32','process':32992}匹配的元素

有谁知道我该如何解决?

解决方法

所有这些代码都可以编写得更加紧凑。请不要直接使用find_windows函数。阅读Getting Started Guide,了解WindowSpecification的工作方式。

app = pwa.Application(backend="win32").connect(found_index=0,title_re=exp,timeout=10)
popup = app.window(found_index=0,title_re=exp)

popup.type_keys('{RIGHT}{ENTER}') # it calls .set_focus() inside

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...